使用 MongoChef GUI,但在命令行中没问题。
我有一个结构如下的集合:
投票数
{
"_id" : "5qgfddRubJ32pS48B",
"createdBy" : "HdKRfwzGriMMZgSQu",
"fellowId" : "yCaqt5nT3LQCBLj8j",
}
我需要先使用 createdBy
字段在用户集合中查找用户,看看他们是否经过验证
用户
{
"_id": "HdKRfwzGriMMZgSQu",
"emails" : [
{
"address" : "someuser@example.com",
"verified" : true
}
]
}
此外,从 fellowId
研究员
{
"_id" : "yCaqt5nT3LQCBLj8j",
"title" : "Fellow Title"
}
并将它们全部导出为一个 csv 或 json 文件。我怎样才能将此作为 mongo 查询/导出来实现?
例如,所需的输出是:
{
"_id" : "yCaqt5nT3LQCBLj8j",
"fellowTitle": "Fellow Title"
"isVerified" : true
}
最佳答案
您可以使用 2 个 $lookup
执行聚合以加入两个集合:
- 1
$lookup
加入用户
- 1
$unwind
删除用户数组 - 1
$unwind
删除用户电子邮件数组(因为我们必须检查verify
) - 1
$sort
使用user.emails.verified
排序 - 1
$group
实际只选择第一个条目(已验证或未验证) - 1
$lookup
加入fellows
- 1
$unwind
删除 fellows 数组 - 1
$project
最后格式化你想要的任何格式 - 1
$out
导出到新集合
查询是:
db.votes.aggregate([{
$lookup: {
from: "users",
localField: "createdBy",
foreignField: "_id",
as: "user"
}
}, {
$unwind: "$user"
}, {
$unwind: "$user.emails"
}, {
$sort: { "user.emails.verified": -1 }
}, {
$group: {
_id: "$_id",
createdBy: { $first: "$createdBy" },
fellowId: { $first: "$fellowId" },
user: { $first: "$user" }
}
}, {
$lookup: {
from: "fellows",
localField: "fellowId",
foreignField: "_id",
as: "fellow"
}
}, {
$unwind: "$fellow"
}, {
$project: {
"_id": 1,
"fellowTitle": "$fellow._id",
"isVerified": "$user.emails.verified"
}
}, {
$out: "results"
}])
然后导出:
mongoexport - d testDB - c results > results.json
关于mongodb - 导出集合并用另一个集合中的字段替换字段(聚合?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40350336/