I have the following documents in two separate collections:
booking: {
user: ObjectID(0)
}
user: {
_id: 0
name: 'John Doe'
}
Is there a way to query for all booking such that in my response, bookings[0].user gives me the full user document instead of just the ObjectID?
Given the following sample data:
Collection "bookings":
{
"_id" : ObjectId("5a78c4517dedc1c2d1b61e3b"),
"booking" : {
"user" : 0
}
}
Collection "users":
{
"_id" : 0,
"name" : "John Doe"
}
You can use $lookup like this:
db.getCollection('bookings').aggregate({
$lookup:
{
from: "users",
localField: "booking.user",
foreignField: "_id",
as: "booking.user"
}
})
This will give you the following result document:
{
"_id" : ObjectId("5a78c4517dedc1c2d1b61e3b"),
"booking" : {
"user" : [
{
"_id" : 0,
"name" : "John Doe"
}
]
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With