Suresh Suresh - 3 months ago 8
Node.js Question

Using mongose aggregation to populate from collection in mongo

Sample document

{
_id:"123",
"completed" : [
{
"Id" : ObjectId("57caae00b2c40dd21ba089be")
"subName" : "oiyt",
"Name" : "Endo",

},
{
"Id" : ObjectId("57caae00b2c40dd21ba089be"),
"subName" : "oiyt",
"Name" : "Endo",
}
]
}


How do I access the
name
and
subname
from
complete
where
_id
matches?

Tom Tom
Answer

You can use $filter or $unwind (or both).

This example shows how to use $filter to get the document only with one matched element in the array, and then $unwind to get easier access to the matched element.

but there are many more options to get the desired result.

db.collection.aggregate([
    {
        $project: {
            filtered_completed: {
                $filter:{
                    input: "$completed",
                    as: "complete",
                    cond: {
                        $eq: [input_id, "$$complete.Id"]
                    }
                }
            }
        }
    },
    {
        $unwind: "$filtered_completed"
        // because we already filtered the 'completed' array, we will get only one document.
        // but you can use it as the first aggreagation pipeline stage and match the _id
    },
    {
        $project: {
            "filtered_completed.Name": 1,
            "filtered_completed.subName": 1
        }
    }
])

read more about $filter and $unwind