2

我创建了一个 ref 集合,其中包含其他集合名称和文档 ID。

所以看起来像

{
   refName: "Collection 1",
   refId: "123123",
},
{
   refName: "Collection 2",
   refId: "456734",
}

集合 1 和集合 2 具有 id 123123 和 456734 的文档。在这种情况下,我想循环所有 ref 集合并使用 mongodb 聚合获取引用的集合数据。

我尝试使用 $lookup 但据说 $lookup 的 $from 必须是字符串文字,而不是变量。

无论如何在MongoDB中处理这种事务?

4

1 回答 1

1

您可以将字符串转换为 int 或将 int 转换为字符串

db.ref.aggregate([
  {
    $addFields: {
      refId: {
        "$toInt": "$refId"
      }
    }
  },
  {
    "$lookup": {
      "from": "coll1",
      "localField": "refId",
      "foreignField": "_id",
      "as": "join"
    }
  }
])

将Mongo操场字符串转换为 Int

使用不相关子查询将Mongo Playground Int工作为字符串

于 2020-12-14T02:33:11.427 回答