我有两个集合,文章和评论,评论中的文章是文章中_id的外键。
db.collection('article').aggregate(
[
{
$lookup:
{
from: "comments",
localField: "_id",
foreignField: "articleId",
as: "comments"
}
},
...
它不起作用,因为文章中的_id是一个ObjectID而articleId是字符串,那该怎么办?
答案 0 :(得分:0)
您可以使用$toObjectId
聚合来实现此目的,该聚合只需将字符串id转换为猫鼬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"
}}
])
答案 1 :(得分:0)
您可以在$toString
字段上直接使用_id
:
db.collection('article').aggregate([
{
$lookup: {
from: "comments",
localField: { $toString : "_id" },
foreignField: "articleId",
as: "comments"
}
},
...
])
但是MongoDB 3.6
不支持聚合管道中的类型转换。因此$toString
和$convert
仅适用于MongoDB 4.0
。