我有两个集合,文章和注释,评论中的articleId是文章中_id的外键。
db.collection('article').aggregate([
  {
    $lookup: {
      from: "comments",
      localField: "_id",
      foreignField: "articleId",
      as: "comments"
    }
  },
  ...
])但是它不起作用,因为文章中的_id是一个ObjectID,articleId是一个字符串。
发布于 2018-07-11 18:52:18
您可以使用$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"
  }}
])发布于 2019-07-06 18:39:31
如果您使用的是MongoDB 4.0或更高版本,那么您可以直接在_id字段上使用$toString:
db.collection('article').aggregate([
  {
    $lookup: {
      from: "comments",
      localField: { $toString : "_id" },
      foreignField: "articleId",
      as: "comments"
    }
  },
  ...
])但是MongoDB 3.6不支持聚合管道内的类型转换。因此,$toString和$convert只适用于MongoDB 4.0。
https://stackoverflow.com/questions/44344711
复制相似问题