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

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

但这是行不通的,因为article中的_idObjectID,而articleId是字符串。

最佳答案

您可以使用 $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"
  }}
])
或使用 $toString 聚合
db.collection('article').aggregate([
  { "$addFields": { "article_id": { "$toString": "$_id" }}},
  { "$lookup": {
    "from": "comments",
    "localField": "article_id",
    "foreignField": "articleId",
    "as": "comments"
  }}
])

关于mongodb - 如何在$ lookup(聚合)中将ObjectID转换为String,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44344711/

10-15 23:49