Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb query using _id object in lookup localField

Tags:

mongodb

we are trying to match _id object to mId foreignfield which is not working. looking for mondodb docs. they do not have anything on this. Is it possible with mongodb query or not?

_id as object in document

   "_id" : ObjectId("56ab6663d69d2d1100c074db"),

mId as String in document

"mId" : "56ab6663d69d2d1100c074db",

query as below:

 collection.aggregate([
                {
                  $lookup:
                    {
                      from: "category",
                      localField: "_id",
                      foreignField: "mId",
                      as: "categories"
                    }
               }
            ])

UDPATE

as a summary, mongodb does not support type coercion in $lookup. so to need above working i have to have _id and mId as ObjectId type in documents itself to make it work.

like image 416
jit Avatar asked Mar 18 '16 06:03

jit


People also ask

What is localField and foreignField in MongoDB?

Perform $lookup with Equality Match: localField: It is any field of input collection the value of which is to be compared which the foreignField value. foreignField: It is any field of from collection the value of which is to be compared which the localField value.

What is localField in MongoDB?

localField. Specifies the field from the documents input to the $lookup stage. $lookup performs an equality match on the localField to the foreignField from the documents of the from collection.

Can we join 2 collections in MongoDB?

For performing MongoDB Join two collections, you must use the $lookup operator. It is defined as a stage that executes a left outer join with another collection and aids in filtering data from joined documents. For example, if a user requires all grades from all students, then the below query can be written: Students.

Does Mongoose populate use lookup?

Mongoose's populate() method does not use MongoDB's $lookup behind the scenes. It simply makes another query to the database. Mongoose does not have functionalities that MongoDB does not have. populate() just makes two or more queries.


1 Answers

From Mongodb 4.0 onwards, you can use $toString aggregation operator to convert ObjectId to string.

Jira issue : Allow $lookup between ObjectId (_id.str) and string


Now your query should be like below :

collection.aggregate([
  { 
    $addFields: { "_id": { "$toString": "$_id" } }
  },
  {
    $lookup: {
      from: "category",
      localField: "_id",
      foreignField: "mId",
      as: "categories"
    }
  }
])
like image 192
Prashant Pokhriyal Avatar answered Sep 24 '22 02:09

Prashant Pokhriyal