2017-06-02 79 views
0

下面我有兩個集合加入兩個集合MongoDB中

db.sample.find().pretty() 
{ 
    "_id" : ObjectId("5930093eb3aaa7c02d4cbcdc"), 
    "name" : "Ashish", 
    "posts" : [ 
      { 
        "_id" : ObjectId("59301c39028afaf3450e2444"), 
        "post" : ObjectId("59301c39028afaf3450e2885") 
      }, 
      { 
        "_id" : ObjectId("59301c39028afaf3450e2445"), 
        "post" : ObjectId("59301c39028afaf3450e2889") 
      } 
    ] 

}

等一個

db.posts.find().pretty() 

{ 「_id」:物件( 「59301c39028afaf3450e2885」), 「頭銜」 :「test1」} {「_id」:ObjectId(「59301c50028afaf3450e2889」),「title」:「test2」}

我想要加入這兩個基於匹配posts._id & sample.post._id值。 &創建顯示「標題」值的結構如下: 總之創建顯示每個用戶喜歡的帖子的結構。

"name" : "Ashish", 
    "posts" : [ 
      { 
        "post" : ObjectId("59301c39028afaf3450e2889"), 
        "title" :"test2" 
      }, 
          { 
        "post" : ObjectId("59301c39028afaf3450e2885"), 
        "title" :"test1" 
      }, 
+0

['$ lookup'(HTTPS: //docs.mongodb.com/manual/reference/operator/aggregation/lookup/)。在您的問題標題的谷歌搜索結果的頂部附近。第五名在我的列表中,前三名是本網站上的以前的答案,第四名是關於總體主題的MongoDB文檔,其中還引用了'$ lookup'。比輸入這篇文章的時間少。 –

回答

0

我們可以加入使用$兩個收集查找一些這樣的事

db.sample.aggregate([ 
{ 
    $lookup: 
    { 
     from: "posts", 
     localField: "posts.post", 
     foreignField: "_id", 
     as: "samplepost" 
    } 
    } 
    ]) 

https://docs.mongodb.com/v3.2/reference/operator/aggregation/lookup/

+0

我使用了你的代碼片段,但標題:「Test1」&Title:輸出中缺少「Test2」字段。 –

+0

samplepost是空的? – Shibon

0

您可以測試它

db.sample.aggregate([ 
    {$unwind: "$posts"}, 
    { 
    $lookup: { 
     from: "posts", 
     localField: "posts.post", 
     foreignField: "_id", 
     as: "post" 
    } 
    }, 
    { 
    $group: { 
     _id: "$_id", 
     name: {$first: "$name"}, 
     posts: { 
     $push: { 
      post: {$arrayElemAt: ["$post._id", 0]}, 
      title: {$arrayElemAt: ["$post.title", 0]} 
     } 
     } 
    } 
    } 
])