node.js - How to use $lookup on embedded document field in mogodb -
please have look, 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"} }, ])
this returns
[ { "_id": "57e3b7f4409d80a508d52769", "author": "tariq", "title": "myfirstpost", "body": "this first post", "user_id": "57e3b763f7bc810c08f9467a", "comments": [ { "title": "hi", "body": "again commenting on this", "user_id": "57e3b763f7bc810c08f9467a", "_id": "57e3c153409d80a508d5276b" }, { "title": "hi", "body": "this seond comment", "user_id": "57e3b763f7bc810c08f9467a", "_id": "57e3c8632ebca0ee0afb2ac6" } ], "__v": 0, "user": [ { "_id": "57e3b763f7bc810c08f9467a", "name": "tariq", "username": "teekay", "password": "123456", "__v": 0 } ] } ]
this return result comparing blog table , user table _id fine .. want userdetail each comment using user_id of “comments.user_id” blog collection , “_id” of collection should this
"_id": "57e3b7f4409d80a508d52769", "author": "tariq", "title": "myfirstpost", "body": "this first post", "user_id": "57e3b763f7bc810c08f9467a", "comments": [ { "title": "hi", "body": "again commenting on this", "user_id": "57e3b763f7bc810c08f9467a", "_id": "57e3c153409d80a508d5276b", "user": [ { "_id": "57e3b763f7bc810c08f9467a", "name": "tariq", "username": "teekay", "password": "123456", "__v": 0 } ] },
you can run aggregation operation of pipeline:
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" }, ])
Comments
Post a Comment