1

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 :)

2
  • so you want query that would transform data and also search for other data to fill it in? i doubt mongo can do that compex things, you can always read IDs from one document and then query for them to get related information. When parsing data, you can use struct that has only fields you are interested in so program don't vaste time with parsing unused fields. Commented Feb 12, 2021 at 12:01
  • Hi @JakubDóka, you can do it very simply with Mongoose in NodeJS .populate('event', 'name') ... so I was hoping there was an equivalent in mgo.v2 for Go. If not then yes, I will have to do multiple queries. Commented Feb 12, 2021 at 12:25

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.