How do I populate a MongoDB array of foreign field IDs?

1.1k Views Asked by At

I have an array of ObjectIds in my MongoDB documents and I'd like to use Go (specifically mgo.v2) to perform a query that populates them with data from the documents that they reference. For example:

{
  _id: ObjectId("some_id"),
  events: [
    ObjectId("referenced_id_1"),
    ObjectId("referenced_id_2")
  ]
}

I'd like the query to return the documents in the following format:

{
  _id: ObjectId("some_id"),
  events: [
    {
      _id: ObjectId("referenced_id_1"),
      name: "some_name_1"
    },
    {
      _id: ObjectId("referenced_id_2"),
      name: "some_name_2"
    }
  ]
}

As far as I can tell I'd need to use $lookup and then $unwind, but can't seem to figure it out. Any help would be very much appreciated! Thanks :)

1

There are 1 best solutions below

0
Flávio Tonon On

I believe you would like to do something like this:

db.getCollection("some_collection").aggregate([
    { $match: { _id: ObjectId("some_id") } },

     // match events ids and then replace field "events" with the matching results
    { $lookup: {
            from: "referenced_collection",
            localField: "events",
            foreignField: "_id",
            as: "events"
    }}

    // there is no need for an $unwind step here since the expected output requires "events" to be an array
])

The query above uses a simplified version of $lookup, supposing you don't need to pre-$project the "events" $lookup results, and neither need to use additional matching keys. If you do need those things, I suggest you take a look on MongoDB's documentation to make the necessary improvements.