I have two collections, article and comments, the articleId
in comments is a foreign key of _id
in article.
db.collection('article').aggregate([
{
$lookup: {
from: "comments",
localField: "_id",
foreignField: "articleId",
as: "comments"
}
},
...
])
but it doesn't work, because _id
in article is an ObjectID
and articleId
is a string.
You can achieve this using $addFields
and $toObjectId
aggregations which simply converts string id to mongo objectId
db.collection('article').aggregate([
{ "$lookup": {
"from": "comments",
"let": { "article_Id": "$_id" },
"pipeline": [
{ "$addFields": { "articleId": { "$toObjectId": "$articleId" }}},
{ "$match": { "$expr": { "$eq": [ "$articleId", "$$article_Id" ] } } }
],
"as": "comments"
}}
])
Or using $toString
aggregation
db.collection('article').aggregate([
{ "$addFields": { "article_id": { "$toString": "$_id" }}},
{ "$lookup": {
"from": "comments",
"localField": "article_id",
"foreignField": "articleId",
"as": "comments"
}}
])
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