如何在$ lookup Mongodb中将字符串转换为LocalField中的objectId [英] How to convert string to objectId in LocalField for $lookup Mongodb

查看:853
本文介绍了如何在$ lookup Mongodb中将字符串转换为LocalField中的objectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在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"}
}

现在我有两个收藏夹

用户包含objectid个用户,例如"_id" : ObjectId("56ab6663d69d2d1100c074db"),

任务,其中包含assignedId作为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屋!

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