2

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.

2
  • You can use the aggregation operator $toObjectId to convert from a string "5e201c4e66cb0c3ede4124d5" to ObjectId. Commented Jan 18, 2020 at 6:50
  • @prasad_ thanks, i tried it but failed. the problem is bundle_items is an array, and i don't want to unWind it, bacause of performance matter. Commented Jan 18, 2020 at 6:52

1 Answer 1

4

You can add below stage before $lookup stage

{
        "$addFields": {
        "bundle_items": {
          "$map": {
                "input": "$bundle_items",
                "in": {
                    id: {
                        "$toObjectId": "$$this.id"
                    }
                }
            }
        }
      }
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.