18

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

Saurabh Sharma
  • 804
  • 6
  • 16
  • 42

1 Answers1

6

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.

HoefMeistert
  • 1,190
  • 8
  • 17
  • 1
    OK..... suppose in tasks collection I do `"assignedId":ObjectId("56ab6663d69d2d1100c074db")` and now I want to get tasks on the basis of assignedId then how I can write query for that...`Task.find({assignedId:ObjectId("56ab6663d69d2d1100c074db")},function(err,data){....})` – Saurabh Sharma Jan 17 '17 at 06:41
  • 1
    When you loop through the results you can do "toString()" on the property to convert the ObjectId => String so you can use it in the next find. like : Task.find({assignedId : yourvar.toString()}, function(err,data){....}) – HoefMeistert Jan 17 '17 at 07:10
  • 1
    I mean ,I have ownerId like `56ab6663d69d2d1100c07‌​4db` and now I want to fetch data from `tasks` collection `Task.find({assignedId : ownerId}, function(err,data){....})` but in tasks collection I have `assignedId` like `ObjectId("56ab6663d69d2d1100c07‌​4db")` then how it will work? how to its will match id's – Saurabh Sharma Jan 17 '17 at 07:29
  • 1
    @SaurabhSharma You can convert a string => ObjectId using : var objectId = require('mongoose').Types.ObjectId; var MyObjectId = new objectId('yourstringobjectid'); – HoefMeistert Jan 17 '17 at 12:12
  • Thanks ...Its working – Saurabh Sharma Jan 17 '17 at 13:10
  • You can't do it in this moment, the request to Mongodb here: https://jira.mongodb.org/browse/SERVER-22781 – chemitaxis Feb 22 '18 at 14:51
  • It is possible in 4.0: https://stackoverflow.com/a/51903659/772290 for answer. – bj97301 Aug 17 '18 at 22:44