如何在 $lookup Mongodb 的 LocalField 中将字符串转换为 objectId [英] How to convert string to objectId in LocalField for $lookup Mongodb
问题描述
我想在 mongodb 中使用 $lookup
添加连接集合.我正在尝试如下
I want to add join collections using $lookup
in mongodb. I am trying as below
{
$lookup:{
from:"User",
localField:"assignedId",
foreignField:"_id",
as:"dataa"}
}
现在我有两个集合
User 包含 "_id" 等用户的
objectid
: ObjectId("56ab6663d69d2d1100c074db"),
User contains objectid
of users like "_id" : ObjectId("56ab6663d69d2d1100c074db"),
和 Tasks,其中包含 assignedId
作为 string
"assignedId":"56ab6663d69d2d1100c074db"
and Tasks where it contains assignedId
as a string
"assignedId":"56ab6663d69d2d1100c074db"
现在,当在两个集合中应用 $lookup 时它不起作用,因为 Id 不匹配.
Now, when applying $lookup in both collection its not working because Id's are not matching.
为此,我用谷歌搜索并找到了一个解决方案
For that I googled it and found a solution that to include
{ $project: {assignedId: {$toObjectId: "$assignedId"} }}
但是这个解决方案对我不起作用,它抛出了一个错误:
but this solution is not working for me, Its throwing an error:
assert: command failed: { "ok" : 0, "errmsg" : "invalid operator '$toObjectId'", "code" : 15999 } : aggregate failed
请帮助我如何解决此问题.
Please help me how can I resolve this issue.
谢谢
推荐答案
在聚合管道中是不可能的.没有转换类型的方法.您可以将 Tasks 集合中的assignedId"类型更改为 ObjectId 吗?否则,您必须在代码中完成,将 ObjectId 转换为 String 并在另一个查询中使用.
It's not possible in the aggregation pipeline. There is no method to convert the type. Can you change the type of "assignedId" in the Tasks collection to ObjectId ? Else you have to do it in code, convert the ObjectId to a String and use in in another query.
这篇关于如何在 $lookup Mongodb 的 LocalField 中将字符串转换为 objectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!