用于填充的聚合查询

我想使用MongoDB聚合来填充comments users 。 我可以很容易地使用它来用$lookup操作符填充createdBy

我的问题是有一种方法可能使用$each聚合$each运算符或类似的东西填充user的注释?

我用Mongo 3.2试了一下,但是在某个地方我看到它将会是3.4中的一个新特性。 我想逃避使用$unwind$groups (我成功地这样做)和类似的东西,以便查询不会变成意大利面代码。

用户

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

post

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

如果你想使用mongodb的 聚合函数,那么你可以使用下面的解决scheme。

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

确保你有使用$ lookup选项的3.2.8或更高版本的mongodb

使用mongoose的填充方法。

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