簡體   English   中英

使用mongodb聚合將子文檔合並到主文檔

[英]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" } }

希望能幫助到你。

要調整文檔的形狀,您需要在管道中添加$project階段,並使用點號訪問子文檔的字段。

{ "$project": { "id": "$pages.id", "field": "$pages.field" } } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM