如何在mogodb中使用$ lookupembedded文档字段

请看看,你的帮助将被appriciated

var user = new Schema({ name: String, }); var Comments = new Schema({ title : String , body : String ,user_id : {type: Schema.Types.ObjectId, ref: 'user' } , date : Date }); var blog = new Schema({ author : String , title : String , body : String , date : Date , user_id :{type: Schema.Types.ObjectId, ref: 'user' } , comments : [Comments] }); db.blogs.aggregate([ { $match : { "_id" : ObjectId("57e3b7f4409d80a508d52769") } }, { $lookup: {from: "users", localField: "user_id", foreignField: "_id", as: "User"} }, ]) 

这返回

 [ { "_id": "57e3b7f4409d80a508d52769", "author": "Tariq", "title": "MyfirstPost", "body": "This is my first post", "user_id": "57e3b763f7bc810c08f9467a", "comments": [ { "title": "hi", "body": "again i am commenting on this", "user_id": "57e3b763f7bc810c08f9467a", "_id": "57e3c153409d80a508d5276b" }, { "title": "hi", "body": "this is seond comment", "user_id": "57e3b763f7bc810c08f9467a", "_id": "57e3c8632ebca0ee0afb2ac6" } ], "__v": 0, "User": [ { "_id": "57e3b763f7bc810c08f9467a", "name": "Tariq", "username": "teekay", "password": "123456", "__v": 0 } ] } ] 

通过比较博客表的这个返回结果是和用户表_id这是好的..但我想通过使用user_id的“comments.user_id”博客收集和集合的“_id”每个评论得到userdetail应该是这样的东西

 "_id": "57e3b7f4409d80a508d52769", "author": "Tariq", "title": "MyfirstPost", "body": "This is my first post", "user_id": "57e3b763f7bc810c08f9467a", "comments": [ { "title": "hi", "body": "again i am commenting on this", "user_id": "57e3b763f7bc810c08f9467a", "_id": "57e3c153409d80a508d5276b", "User": [ { "_id": "57e3b763f7bc810c08f9467a", "name": "Tariq", "username": "teekay", "password": "123456", "__v": 0 } ] }, 

您可以运行pipe道的聚合操作:

 db.blogs.aggregate([ { "$unwind": "$comments" }, { "$lookup": { "from": "users", "localField": "comments.user_id", "foreignField": "_id", "as": "comments.user" } }, { "$unwind": "$comments.user" }, { "$group": { "_id": "$_id", "author": { "$first": "$author" }, "title": { "$first": "$title" }, "body": { "$first": "$body" }, "comments": { "$push": "$comments" }, "user_id": { "$first": "$user_id" } } }, { "$lookup": { "from": "users", "localField": "user_id", "foreignField": "_id", "as": "user" } }, { "$unwind": "$user" }, ])