【发布时间】:2018-02-01 19:36:25
【问题描述】:
我有 2 个集合 coll1 和 coll2。我想在字段“_id”和“comm_field”上应用 $lookup,所以我使用了查询:
db.coll1.aggregate([
{
$lookup:
{
from: "coll2",
localField: "_id",
foreignField: "comm_field",
as: "inventory_docs"
}
},
{
$project:{"_id" : 0, "inventory_docs" : 1}
},
{ $unwind:"$inventory_docs"}
])
得到的输出为:
/* 1 */
{
"inventory_docs" : {
"_id" : ObjectId("ssdfsfsdfsdfsfsdfsdfsdfsfsdf"),
"comm_field" : NumberLong(1111),
"status" : "active"
}
}
/* 2 */
{
"inventory_docs" : {
"_id" : ObjectId("erteterterterterterterterter"),
"comm_field" : NumberLong(1111),
"status" : "active"
}
}
/* 3 */
{
"inventory_docs" : {
"_id" : ObjectId("vbvbfvbdbbcvbvcbcdrgvbcbcbcv"),
"comm_field" : NumberLong(2222),
"status" : "active"
}
}
有什么方法可以让我看到如下输出:
{
"_id" : ObjectId("ssdfsfsdfsdfsfsdfsdfsdfsfsdf"),
"comm_field" : NumberLong(1111),
"status" : "active"
}
{
"_id" : ObjectId("erteterterterterterterterter"),
"comm_field" : NumberLong(1111),
"status" : "active"
}
{
"_id" : ObjectId("vbvbfvbdbbcvbvcbcdrgvbcbcbcv"),
"comm_field" : NumberLong(2222),
"status" : "active"
}
所以基本上我希望我的输出格式为 {---},而不是 {"inventory_docs":{---}}
【问题讨论】:
-
使用
$replaceRoot或简单的$project字段返回子属性“之后”执行$unwind。将$project放置在“之前”并没有真正获得太多收益,或者至少没有您认为的那么多收益。将$unwind直接放在$lookup之后实际上是pipeline optimization,它将$unwind“提升”为$lookup本身。 -
成功了。谢谢@NeilLunn
-
@NeilLunn $replaceRoot 有效,但 $project 无效。根据您的建议,我使用嵌入的文档值更改了 $unwind 和 $project 的顺序。但仍然无法摆脱格式 {"inventory_docs":{---}}。我现在正在使用这个查询: db.coll1.aggregate([ { $lookup: { from: "coll2", localField: "_id", foreignField: "comm_field", as: "inventory_docs" } }, { $unwind:" $inventory_docs"}, { $project:{"_id" : 0, "inventory_docs._id" : 1, "inventory_docs.comm_field" : 1, "inventory_docs.status" : 1}} ])
标签: mongodb aggregation-framework