Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB replace an ObjectID reference in a document with the referenced document?

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?

like image 277
BeardMagician Avatar asked Oct 31 '25 23:10

BeardMagician


1 Answers

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"
            }
        ]
    }
}
like image 133
dnickless Avatar answered Nov 03 '25 14:11

dnickless