Amin Shojaei
Amin Shojaei

Reputation: 6518

convert a field inside an array of objects. mongodb aggregation

I have a document like this:

{
    "_id" : ObjectId("5e22a400d4abfae27d173292"),
    "bundle_items" : [ 
        {
            "id" : "5e201c30d4abfae27d171851"
        }, 
        {
            "id" : "5e201c3dd4abfae27d171862"
        }, 
        {
            "id" : "5e201c4e66cb0c3ede4124d5"
        }
    ]
}

And my aggregation is:

[
        {
            $lookup : {
                from : 'product',
                localField   : 'bundle_items.id', // problem is here, i need this field to be ObjectId
                foreignField : '_id',
                as: 'bundle_items_objects'    
            }
        },{
            $project: {
                'bundle_total_regular_prices': {
                '$sum': '$bundle_items_objects.regular_price'
                },
                'bundle_items' : 1,
            }
        }
]

How can i convert bundle_items.*.id to ObjectId in my aggregation?

i can't change it on database because of some reasons.

Upvotes: 2

Views: 1681

Answers (1)

Ashh
Ashh

Reputation: 46441

You can add below stage before $lookup stage

{
        "$addFields": {
        "bundle_items": {
          "$map": {
                "input": "$bundle_items",
                "in": {
                    id: {
                        "$toObjectId": "$$this.id"
                    }
                }
            }
        }
      }
  }

Upvotes: 4

Related Questions