Home > Software design >  How to populate a field inside array with aggregation
How to populate a field inside array with aggregation

Time:09-23

here is the query that I used to return an object from array of elements by using the _id. It looks like this,

db.users.aggregate([
    {$match: { "business_idea._id": ObjectId('613ee10818bc570bceb1d060') }},
    {$project: {
        business_idea: {$filter: {
            input: '$business_idea',
            as: 'bi',
            cond: { $eq: ["$$bi._id", ObjectId('613ee10818bc570bceb1d060') ] }
        }}
    }}
])

This query produces output like this,

{
    "_id" : ObjectId("613e418f19968b0652bbbb24"),
    "business_idea" : [
        {
            "business_tags" : [
                ObjectId("613ee063b11cee0b7dde1086")
            ],
            "_id" : ObjectId("613ee10818bc570bceb1d060"),
            "business_id" : "613ee10818bc570bceb1d05f",
            "business_name" : "Business_2",
            "business_type" : "No type",
            "business_desc" : "desc, desc-2",
            "business_logo" : "https://neur-dev.s3.ap-south-1.amazonaws.com/logo/21091631510791555.jpeg",
            "isDeleted" : false,
            "business_name_to_lower" : "business_2"
        }
    ]
}

Now I just want to populate the real value of business_tags from businesstags collection by using _id.

can anyone help me with this, Thanks.

CodePudding user response:

To find related tags you must get them by $lookup aggregate like this:


{
"$lookup":{
  from: 'businesstags',
  localField: 'business_tags',
  foreignField: '_id',
  as: 'new_tags'
}
}
  • Related