mongodbmongodb-queryaggregation-frameworkmongojs

Find documents matching ObjectIDs in a foreign array


I have a collection Users:

{
  _id: "5cds8f8rfdshfd"
  name: "Ted"
  attending: [ObjectId("2cd9fjdkfsld")]
}

I have another collection Events:

{
  _id: "2cd9fjdkfsld"
  title: "Some Event Attended"
},
{
  _id: "34dshfj29jg"
  title: "Some Event NOT Attended"
}

I would like to return a list of all events being attended by a given user. However, I need to do this query from the Events collection as this is part of a larger query.

I have gone through the following questions:

I have tried various ways of modifying the above answers to fit my situation but have been unsuccessful. The second answer from the third question gets me closest but I would like to filter out unmatching results rather than have them returned with a value of 0.

My desired output:

[
  {
    _id: "2cd9fjdkfsld"
    title: "Some Event Attended"
  },
]

Solution

  • One option would be like this:

    db.getCollection('Events').aggregate({
        $lookup: // join
        {
            from: "Users", // on Users collection
            let: { eId: "$_id" }, // keep a local variable "eId" that points to the currently looked at event's "_id"
            pipeline: [{
                $match: { // filter where
                    "_id": ObjectId("5c6efc937ef75175b2b8e7a4"), // a specific user
                    $expr: { $in: [ "$$eId", "$attending" ] } // attends the event we're looking at
                }
            }],
            as: "users" // push all matched users into the "users" array
        }
    }, {
        $match: { // remove events that the user does not attend
            "users": { $ne: [] }
        }
    })
    

    You could obviously get rid of the users field by adding another projection if needed.