简体   繁体   中英

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?

You can use shorthand $toObjectId in mongo version 4.0.

Something like

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

ObjectId is a constructor for ObjectIds in the shell. When you write something like

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

the mongo shell evaluates ObjectId("$$id") before sending the aggregation request. It's just like if you called a function in Javascript like

var x = 2
var y = 4
f(x + y) // f(6)

What you need is an aggregation operator to convert a string into an ObjectId. Unfortunately, no such function exists, as of MongoDB 2.6. Why do you need to convert the string? What are you going to do with it? Maybe there is a way around the lack of a conversion operator in aggregation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM