MongoDB聚合项目字符串转换为ObjectId [英] MongoDB aggregation project string to ObjectId

查看:1465
本文介绍了MongoDB聚合项目字符串转换为ObjectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在聚合查询中将十六进制字符串转换为其等效的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"
        }
    }
]);

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

无论哪种方法,我都会不断收到错误错误:无效的对象ID:长度".我测试了添加文字字符串来代替聚合变量,并且得到了带有正确ObjectID的结果.似乎字符串值没有传递给Mongo的ObjectId函数,而是将变量名作为文字字符串传递.

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?

推荐答案

ObjectId是Shell中ObjectId的构造函数.当你写类似

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

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

mongo shell在发送聚合请求之前评估ObjectId("$$id").就像您在Javascript中调用函数一样

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)

您需要的是一个聚合运算符,用于将字符串转换为ObjectId.不幸的是,从MongoDB 2.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.

这篇关于MongoDB聚合项目字符串转换为ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆