Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB aggregation project string to ObjectId

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?

like image 853
StevenWarren Avatar asked Dec 19 '14 17:12

StevenWarren


People also ask

How to convert a string to an objectId in MongoDB?

From MongoDB 4.0, you can use the $toObjectId aggregation pipeline operator to convert a string to an ObjectId. The string must be a hexadecimal string of length 24. Suppose we have a collection called foo and it contains the following document: We can use the $toObjectId operator to convert the bar field to an ObjectId.

Why can't I convert a string value to objectId?

You cannot convert a string value that is not a hexadecimal string of length 24. The following aggregation operation on the orders collection converts the _id to ObjectId before sorting by the value: If the conversion operation encounters an error, the aggregation operation stops and throws an error.

How to apply $concat in aggregation on ObjectIDs?

You can simply use $toString to apply $concat in aggregation on ObjectIDs in the following way - Show activity on this post. this may match the data with both fields to the filter.


1 Answers

You can use shorthand $toObjectId in mongo version 4.0.

Something like

db.omvas.aggregate([
   {"$project":{"EID":{"$toObjectId":"$EID"}}
])
like image 71
s7vr Avatar answered Sep 19 '22 11:09

s7vr