【问题标题】:How to convert ObjectID to String in $lookup (aggregation)如何在 $lookup 中将 ObjectID 转换为字符串(聚合)
【发布时间】:2017-11-04 19:07:14
【问题描述】:

我有两个集合,article和cmets,cmets中的articleId是article中_id的外键。

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

但它不起作用,因为文章中的_idObjectIDarticleId 是一个字符串。

【问题讨论】:

  • 你不能。不可能在聚合管道中“强制转换”任何类型。您需要修复数据,以便“字符串”实际上是 ObjectId 值。

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

您可以使用 $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"
  }}
])

【讨论】:

  • 有没有办法以类似的方式将foreignField或connectToField(使用graphLookup)从ObjectId转换为String?
【解决方案2】:

如果您使用的是 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

【讨论】:

    猜你喜欢
    • 2016-09-25
    • 1970-01-01
    • 2017-06-01
    • 2020-09-19
    • 2014-12-08
    • 2022-01-02
    • 2017-05-21
    • 2011-12-11
    • 2018-11-09
    相关资源
    最近更新 更多