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

查看:24
本文介绍了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 中 ObjectIds 的构造函数.当你写类似的东西时

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天全站免登陆