Create an ObjectId with a variable

Hello !

I’m trying to convert a string field (NID) to an ObjectId

All NID field for each documents looks something like this “58c59c6a99d4ee0af9e0c325”
So 24 character.

I tried this aggregation :

{
    "convert_NID": { 
        "$let": {
           "vars" : { 
               "id": "$NID" 
               },
           "in" : ObjectId("$$id")
        }
    }
}

But come up with error :

Illegal ObjectId : argument must be a 24 character hexadecimal

I tried to look at my variable by changing ObjectId(“$$id”) with “$$id” and everything looks good. I get my field “convert_NID” with my 24 character string for each document.

So what’s the problem ?

Hi @Henry, welcome!

The problem here is that ObjectId() is a client side method (i.e. mongo shell) and not an aggregation operator/method that is able to resolve the $$id reference on the aggregation pipeline execution.

If you’re MongoDB server version is v4.0+, you could utilise $toObjectId aggregation pipeline operator to convert 24-long hexadecimal string to an ObjectId.

Regards,
Wan.

3 Likes

Hi @wan !

Thank you for your answer, it’s great.
I was about to select your reply as the solution but perhaps I can ask for more help if I may.

The company for which I work for is working on MongoDB 3.6, so I don’t have access to your operator, and our database won’t be upgraded soon. For the meantime, is there another solution ?

Hi @Henry,

Depending on the use case, you could utilise any of MongoDB drivers to write a client side script to either update the field to ObjectId() format or to add a new field that contains the ObjectId() value.

Regards,
Wan.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.