2016-06-30 184 views
0

下面是我收集的樣本記錄:合併子文檔主文檔與MongoDB的聚集

{ 
    _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操作將子文檔合併到主文檔中嗎?

+0

您列爲所需輸出的結果格式不正確。我不知道如何實現它。 – Tiramisu

+1

@Tiramisu我更新了格式 – nikoss

+1

在'$ unwind'後添加'{「$ project」:{「id」:「$ pages.id」,「field」:「$ pages.field」}}''陣列。 – styvane

回答

1

要重塑您的文檔,您需要在管道中添加$project階段,並使用dot notation訪問子文檔的字段。

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

這是我的方法,它是一些更接近您的預期結果。

我的樣本數據

"_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後([{$開卷: 「$頁」}])

"_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" } } 

加入$組到管道

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" } } 

希望它有助於。

+0

以及這不正是我所尋求的仍然是不合併到主要我猜他們沒有辦法做到這一點 – nikoss

相關問題