本文介绍了数据有限的$ lookup聚合的MongoDb Post格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个集合coll1和coll2。我想在字段 _id和 comm_field上应用$ lookup,所以我使用了查询:
I have 2 collection coll1 and coll2. I want to apply $lookup on fields "_id" and "comm_field" so I used the query:
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"
}
}
有没有什么办法可以让我看到输出,如:
Is there any way by which i can see the output like:
{
"_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:{---}}
So basically I want my output in format {---}, not in {"inventory_docs":{---}}
推荐答案
尼尔的答案奏效了。 {$ replaceRoot:{newRoot: $ inventory_docs}}
的添加完成了工作。谢谢尼尔。
Neil's answer worked. Addition of { $replaceRoot: { newRoot: "$inventory_docs" } }
did the job. Thanks Neil.
db.coll1.aggregate([
{
$lookup:
{
from: "coll2",
localField: "_id",
foreignField: "comm_field",
as: "inventory_docs"
}
},
{
$project:{"_id" : 0, "inventory_docs" : 1}
},
{ $unwind:"$inventory_docs"},
{ $replaceRoot: { newRoot: "$inventory_docs" } }
])
这篇关于数据有限的$ lookup聚合的MongoDb Post格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!