2016-11-22 58 views
4

我想使用MongoDB聚合来填充userscomments。我可以很容易地将它用于与$lookup运算符一起填充createdBy用于填充的聚合查询

我的问题是有没有办法可能使用$each运营商在聚合或类似的东西填充user的评论?

我用Mongo 3.2试过了,但是在某个地方我看过它将会是3.4版本的新功能? 我想转义使用$unwind$groups(我成功地做到了这一点)和类似的事情,以便查询不会变成意大利面代码。

用户

{ 
    "_id" : ObjectId("582c31d4afd9252c8515a88b"), 
    "fullName": "test1" 
}, 
{ 
    "_id" : ObjectId("582c3db0afd9252c8515a88d"), 
    "fullName": "test2" 
} 

帖子

{ 
    "_id" : ObjectId("5829cac7e9c0994d3db718f8"), 
    "imgUrl": "images/test.jpg", 
    "createdBy": ObjectId("582c31d4afd9252c8515a88b"), 
    "comments": [ 
     { 
      "_id" : ObjectId("5829cab8e9c0994d3db718f7"), 
      "content": "blabla", 
      "user": ObjectId("582c31d4afd9252c8515a88b") 
     } 
    ] 
} 

预期输出:的

{ 
    "_id" : ObjectId("5829cac7e9c0994d3db718f8"), 
    "imgUrl": "images/test.jpg", 
    "createdBy": ObjectId("582c31d4afd9252c8515a88b"), 
    "comments": [ 
     { 
      "_id" : ObjectId("5829cab8e9c0994d3db718f7"), 
      "content": "blabla", 
      "user": { 
         "_id" : ObjectId("582c31d4afd9252c8515a88b"), 
         "fullName": "test1" 
        } 
     } 
    ] 
} 
+0

我不明白你的问题。你能否详细说明一下? – styvane

+0

@Styvane字段'用户'就像是“FK”,我想重写'用户'集合中的所有字段。 这是我想要的结果... https://postimg.org/image/3n9bb9u0p/ –

+0

请问你[编辑链接](http://stackoverflow.com/posts/40736869/edit)对你的问题添加预期的输出(document not image) – styvane

回答

1

如果你想使用MongoDB的聚集功能,那么你可以使用下面的解决方案。

db.getCollection('posts').aggregate([ 
    {"$unwind":{"path":"$comments","preserveNullAndEmptyArrays":true}}, 
    { $lookup: 
      { 
       from: 'users', 
       localField: 'comments.user', 
       foreignField:'_id', 
       as: 'comments.user' 
      } 
    }, 
    {"$unwind":{"path":"$comments.user","preserveNullAndEmptyArrays":true}}, 
    { 
      $group : { 
       _id : "$_id", 
       comments : {$push : "$comments"}, 
       imgUrl : {$first : "$imgUrl"}, 
       createdBy : {$first : "$createdBy"} 
      } 
    } 

]) 

请确保您有3.2.8或更高版本的MongoDB使用$查找选项

0

使用填入方法猫鼬。

db.collections.find({}).populate([{path:"comments.user"}]). 
+0

我想用本地mongo来做。 –