How to convert string to objectId in LocalField for $lookup Mongodb

Saurabh Sharma picture Saurabh Sharma · Jan 17, 2017 · Viewed 8.6k times · Source

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

Answer

HoefMeistert picture HoefMeistert · Jan 17, 2017

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.