You can use $lookup (multiple) to get records from multiple collections:
Example:
If you have more collections (I have 3 collections for demonstration here, you may have more than 3). and I want to get data from 3 collections in one object:
The collection looks like this:
db.doc1.find () is pretty () ;.
{ "_id" : ObjectId("5901a4c63541b7d5d3293766"), "firstName" : "shubham", "lastName" : "verma" }
db.doc2.find () is pretty () ;.
{ "_id" : ObjectId("5901a5f83541b7d5d3293768"), "userId" : ObjectId("5901a4c63541b7d5d3293766"), "address" : "Gurgaon", "mob" : "9876543211" }
db.doc3.find () is pretty () ;.
{ "_id" : ObjectId("5901b0f6d318b072ceea44fb"), "userId" : ObjectId("5901a4c63541b7d5d3293766"), "fbURLs" : "http://www.facebook.com", "twitterURLs" : "http://www.twitter.com" }
Your request will now look like this:
db.doc1.aggregate([ { $match: { _id: ObjectId("5901a4c63541b7d5d3293766") } }, { $lookup: { from: "doc2", localField: "_id", foreignField: "userId", as: "address" } }, { $unwind: "$address" }, { $project: { __v: 0, "address.__v": 0, "address._id": 0, "address.userId": 0, "address.mob": 0 } }, { $lookup: { from: "doc3", localField: "_id", foreignField: "userId", as: "social" } }, { $unwind: "$social" }, { $project: { __v: 0, "social.__v": 0, "social._id": 0, "social.userId": 0 } } ]).pretty();
Then your result will be:
{ "_id" : ObjectId("5901a4c63541b7d5d3293766"), "firstName" : "shubham", "lastName" : "verma", "address" : { "address" : "Gurgaon" }, "social" : { "fbURLs" : "http://www.facebook.com", "twitterURLs" : "http://www.twitter.com" } }
If you need all the entries from each collection, you should remove the line below from the query:
{ $project: { __v: 0, "address.__v": 0, "address._id": 0, "address.userId": 0, "address.mob": 0 } } { $project: { "social.__v": 0, "social._id": 0, "social.userId": 0 } }
After deleting the code, you will get the full entry:
{ "_id" : ObjectId("5901a4c63541b7d5d3293766"), "firstName" : "shubham", "lastName" : "verma", "address" : { "_id" : ObjectId("5901a5f83541b7d5d3293768"), "userId" : ObjectId("5901a4c63541b7d5d3293766"), "address" : "Gurgaon", "mob" : "9876543211" }, "social" : { "_id" : ObjectId("5901b0f6d318b072ceea44fb"), "userId" : ObjectId("5901a4c63541b7d5d3293766"), "fbURLs" : "http://www.facebook.com", "twitterURLs" : "http://www.twitter.com" } }