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.
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.
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.
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.
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.
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"
}
}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With