在mongoDB中加入两个集合

时间:2017-06-02 07:33:55

标签: mongodb join

我有两个集合

 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" :ObjectId(" 59301c39028afaf3450e2885")," title" :" test1" } {" _id" :ObjectId(" 59301c50028afaf3450e2889")," title" :" test2" }

我希望根据匹配的posts._id和amp;来加入这两个sample.post._id值。 &安培;创建结构显示"标题"价值如下: 简而言之,创建显示每个用户喜欢的帖子的结构。

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

2 个答案:

答案 0 :(得分:0)

我们可以使用$ lookup加入两个集合,比如这个

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

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

答案 1 :(得分: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]}
        }
      }
    }
  }
])
相关问题