2017-06-02 80 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]} 
     } 
     } 
    } 
    } 
])