我有兩個集合,文章和評論,評論中的文章是文章中_id的外鍵.
db.collection('article').aggregate(
[
{
$lookup:
{
from: "comments",
localField: "_id",
foreignField: "articleId",
as: "comments"
}
},
...
它不起作用,因為文章中的_id是一個ObjectID而articleId是字符串,那怎么辦?
您可以使用
$toObjectId聚合實現此目的,該聚合僅將字符串ID轉換為mongoose 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"
}}
])
或者使用$toString聚合
db.collection('article').aggregate([
{ "addFields": { "article_id": { "$toString": "$_id" }}},
{ "$lookup": {
"from": "comments",
"localField": "article_id",
"foreignField": "articleId",
"as": "comments"
}}
])
