使用MongoChef GUI但命令行很好。
我有一个具有结构的集合:
<div id="container">
<div className="horizontal-centered">Center this</div>
</div>
我需要先使用{
"_id" : "5qgfddRubJ32pS48B",
"createdBy" : "HdKRfwzGriMMZgSQu",
"fellowId" : "yCaqt5nT3LQCBLj8j",
}
字段在用户集合中查找用户,看看他们是否已经过验证
createdBy
另外,从{
"_id": "HdKRfwzGriMMZgSQu",
"emails" : [
{
"address" : "someuser@example.com",
"verified" : true
}
]
}
fellowId
并将它们全部导出为一个csv或json文件。我怎样才能实现这个mongo查询/导出?
所需的输出将是,例如:
{
"_id" : "yCaqt5nT3LQCBLj8j",
"title" : "Fellow Title"
}
答案 0 :(得分:5)
您可以使用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"
}])
然后导出:
mongoexport - d testDB - c results > results.json