BeardMagician
BeardMagician

Reputation: 657

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?

Upvotes: 4

Views: 1738

Answers (2)

millenion
millenion

Reputation: 1907

Accepted answer is great, so just in case someone is wondering how to get user as an object and not an array, you can use $unwind stage right after:

db.getCollection('bookings').aggregate([
  {
    $lookup: {
       from: "users",
       localField: "booking.user",
       foreignField: "_id",
       as: "booking.user"
     }
  },
  {
    $unwind: "$booking.user"
  }
])

This will result in the following document:

{
    "_id" : ObjectId("5a78c4517dedc1c2d1b61e3b"),
    "booking" : {
        "user" : {
            "_id" : 0,
            "name" : "John Doe"
        }
    }
}

Upvotes: 1

dnickless
dnickless

Reputation: 10918

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"
            }
        ]
    }
}

Upvotes: 4

Related Questions