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?
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.
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.
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.
You can use shorthand $toObjectId
in mongo version 4.0.
Something like
db.omvas.aggregate([
{"$project":{"EID":{"$toObjectId":"$EID"}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With