0

I'm trying to get an array of id's from a document in a collection(Users) and then get their names by finding the document with that id in another collection(Benefits).

I've tried reading up on $lookup but the documention is confusing, as it doesn't give a real world example.

This returns the benefit's from the user, which I can grasp.

Users.findOne({username: req.params.username},{benefits: 1, _id: 0 }, function(err, user) {
 if(err)
   console.log(err);
 else
   res.json(user);
});

This is a collection example of the user which contains an array of IDs.

{
    "_id" : ObjectId("5b997cf8082be41757b6d733"),
    "username" : "anonuser",
    "benefitsIds" : [ 
        ObjectId("5ba8345f1e56fe8e6caaaa07"), 
        ObjectId("5ba706d64e82292e72e9ae71")
    ]
}

Now in the other collection(Benefits) I have the benefits with their names. This is a collection example.

{
    "_id" : ObjectId("5ba706d64e82292e72e9ae71"),
    "benefit_name" : "Dental"
}

I just want to return the actual benefit name.

SV3
  • 3
  • 4
  • Edit: Not a duplicate of what you posted @chridam. Hard to relate to my example. I'm looking for an example using my code as it's not the same as anything I could search for. Thanks. – SV3 Oct 12 '18 at 06:28
  • From the answers you can deduce the pipeline: `Users.aggregate([ { "$match": { "username" : req.params.username } }, { "$lookup": { "from": "benefits", "localField": "benefitsIds", "foreignField": "_id", "as": "benefits" } }, { "$project": { "benefits": "$benefits.benefit_name", "_id": 0 } } ], (err, result) => console.log(result))` – chridam Oct 12 '18 at 07:22
  • Thank you! Moving from SQL to Mongo is... interesting. – SV3 Oct 12 '18 at 17:20

1 Answers1

0
db.users.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $unwind: {
                path: "$benefitsIds"

            }
        },

        // Stage 2
        {
            $lookup: // Equality Match
            {
                from: "benefits",
                localField: "benefitsIds",
                foreignField: "_id",
                as: "benefits"
            }


        }

    ]



);
Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26