MongoDB aggregation project string to ObjectId

aggregation-frameworkmongodb

I am attempting to convert a hexadecimal string to its equivalent ObjectID in an aggregation query. I tried two different methods:

db.omvas.aggregate([
    {$project:{
        EID:{$let: {
               vars: {
                  id:  "$EID"
               },
               in: ObjectId("$$id")
            }},
        }
    },
    {$group:{
        _id:"$EID"
        }
    }
]);

and

db.omvas.aggregate([
    {$project:{
        EID: ObjectId("$EID")
        }
    },
    {$group:{
        _id:"$EID"
        }
    }
]);

I keep getting the error "Error: invalid object id: length" using either method. I tested adding a literal string in place of the aggregation variable and I get a result with a proper ObjectID. It seems that the string value is not being passed through to Mongo's ObjectId function but rather the variable name is being passed as a literal string.

Anyone have any idea if what I am trying to accomplish is possible? Is there some magic I am missing?

Best Answer

You can use shorthand $toObjectId in mongo version 4.0.

Something like

db.omvas.aggregate([
   {"$project":{"EID":{"$toObjectId":"$EID"}}
])