elz*_*lzi 2 database mongodb meteor mongodb-query aggregation-framework
使用MongoChef GUI但在命令行中很好.
我有一个结构的集合,因此:
{
"_id" : "5qgfddRubJ32pS48B",
"createdBy" : "HdKRfwzGriMMZgSQu",
"fellowId" : "yCaqt5nT3LQCBLj8j",
}
Run Code Online (Sandbox Code Playgroud)
我需要首先使用该createdBy字段在用户集合中查找用户,以查看它们是否已经过验证
{
"_id": "HdKRfwzGriMMZgSQu",
"emails" : [
{
"address" : "someuser@example.com",
"verified" : true
}
]
}
Run Code Online (Sandbox Code Playgroud)
此外,从第三个集合中获取更多信息 fellowId
{
"_id" : "yCaqt5nT3LQCBLj8j",
"title" : "Fellow Title"
}
Run Code Online (Sandbox Code Playgroud)
并将它们全部导出为一个csv或json文件.我怎样才能实现这个mongo查询/导出?
所需的输出将是,例如:
{
"_id" : "yCaqt5nT3LQCBLj8j",
"fellowTitle": "Fellow Title"
"isVerified" : true
}
Run Code Online (Sandbox Code Playgroud)
您可以使用2执行聚合$lookup以加入两个集合:
$lookup加入users$unwind删除用户数组$unwind删除用户电子邮件数组(因为我们要检查verify)$sort排序user.emails.verified$group实际上只选择第一个条目(已验证或未验证)$lookup加入fellows$unwind删除研究员数组$project格式化你想要的格式$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"
}])
Run Code Online (Sandbox Code Playgroud)
然后导出:
mongoexport - d testDB - c results > results.json
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1185 次 |
| 最近记录: |