![](/img/trans.png)
[英]MongoDB : add New Field to existing sub document after $look stage or merge lookup response to main document
[英]Merge a sub document to main document with mongodb aggregation
這是我收藏的樣本記錄:
{
_id:someId,
pages:[
{id:id,field:value},
{id:otherId,field:otherValue}
]
}
這是我在做什么:
collection.aggregate([
{$unwind:"$pages"}
])
其結果類似於:
{
_id:id,
pages:{id:id,field:value}
},
{
_id:id,
pages:{id:otherId,field:otherValue}
}
但是,我想要實現的是:
{
_id:id,
id:id,
field:value
},
{
_id:id,
id:otherId,
field:otherValue
}
我可以用$project
操作來做一些事情來將子文檔合並到主文檔中嗎?
這是我的方法,它更接近您的預期結果。
我的樣本數據
"_id" : 1,
"pages" : [
{
"_id" : "a",
"comment" : "Have a Nice Day"
},
{
"_id" : "b",
"comment" : "Everyday is Beautiful"
},
{
"_id" : "c",
"comment" : "All is Well"
},
{
"_id" : "d",
"comment" : "Nature is wonderful"
},
{
"_id" : "e",
"comment" : "Enjoy the moment"
}
]
執行db.collection.aggregate([{$$ unwind:“ $ pages”}])之后
"_id" : 1, "pages" : { "_id" : "a", "comment" : "Have a Nice Day" } }
"_id" : 1, "pages" : { "_id" : "b", "comment" : "Everyday is Beautiful" } }
"_id" : 1, "pages" : { "_id" : "c", "comment" : "All is Well" } }
"_id" : 1, "pages" : { "_id" : "d", "comment" : "Nature is wonderful" } }
"_id" : 1, "pages" : { "_id" : "e", "comment" : "Enjoy the moment" } }
然后將$ group添加到管道中
db.collectiom.aggregate([[$$ unwind:“ $ pages”},{$ group:{_ id:“ $ pages”}}]));
"_id" : { "_id" : "e", "comment" : "Enjoy the moment" } }
"_id" : { "_id" : "d", "comment" : "Nature is wonderful" } }
"_id" : { "_id" : "c", "comment" : "All is Well" } }
"_id" : { "_id" : "b", "comment" : "Everyday is Beautiful" } }
"_id" : { "_id" : "a", "comment" : "Have a Nice Day" } }
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.