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

I want to add a collection of collections using $lookup in mongodb. I try as below

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

I now have two collections

The user contains the objectid of users such as "_id" : ObjectId("56ab6663d69d2d1100c074db"),

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

Now, applying $ lookup in both assemblies, it does not work, because Id does not match.

For this, I googled and found a solution that includes

{ $project: { assignedId: {$toObjectId: "$assignedId"} }}

but this solution does not work for me, its error:

 assert: command failed: { "ok" : 0, "errmsg" : "invalid operator '$toObjectId'", "code" : 15999 } : aggregate failed 

Please help me how can I solve this problem.

thanks

+6
source share
1 answer

This is not possible in the aggregation pipeline. There is no type conversion method. Can you change the type "assignId" in the "Tasks" collection to ObjectId? Otherwise, you must do this in code, convert the ObjectId to String, and use it in another request.

+2
source

Source: https://habr.com/ru/post/1014137/


All Articles