如何在$ lookup(聚合)中将ObjectID转换为String

cit*_*ice 5 mongodb mongodb-query aggregation-framework

我有两个集合,文章和评论,评论中的文章是文章中_id的外键.

db.collection('article').aggregate([
  {
    $lookup: {
      from: "comments",
      localField: "_id",
      foreignField: "articleId",
      as: "comments"
    }
  },
  ...
])
Run Code Online (Sandbox Code Playgroud)

它不起作用,因为文章中的_id是一个ObjectID而articleId是字符串,那怎么办?

Ash*_*shh 14

您可以使用$addFields$toObjectId聚合来实现这一点,它只是将字符串 id 转换为 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"
  }}
])
Run Code Online (Sandbox Code Playgroud)

或者使用$toString聚合

db.collection('article').aggregate([
  { "$addFields": { "article_id": { "$toString": "$_id" }}},
  { "$lookup": {
    "from": "comments",
    "localField": "article_id",
    "foreignField": "articleId",
    "as": "comments"
  }}
])
Run Code Online (Sandbox Code Playgroud)