How to convert string to objectId in LocalField for $lookup Mongodb [duplicate]

橙三吉。 提交于 2019-11-27 03:51:30

问题


I want to add join collections using $lookup in mongodb. I am trying as below

{
 $lookup:{
   from:"User",
   localField:"assignedId",
   foreignField:"_id",
   as:"dataa"}
}

Now I have two collections

User contains objectid of users like "_id" : ObjectId("56ab6663d69d2d1100c074db"),

and Tasks where it contains assignedId as a string "assignedId":"56ab6663d69d2d1100c074db"

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.

Thanks


回答1:


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.



来源:https://stackoverflow.com/questions/41689349/how-to-convert-string-to-objectid-in-localfield-for-lookup-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!