MongoDB 聚合 - 不从查找集合中获取数据

问题描述 投票:0回答:1

我知道数据建模是错误的。我没有做到,我来的时候是这样的 现在我需要加入两个集合。 类别:

[{
  "_id": "5f77502b36e4460d2b90aa24",
  "name": "Category-873441698",
  "inclusionDate": "2018-11-02T00:00:00.000Z"
}]

和项目:

[{
    "_id" : ObjectId("5d1f824683630f0001d9dc7f"),
    "name" : "project-199986030",
    "categoryId" : "5f77502b36e4460d2b90aa24",
    "inclusionDate" : ISODate("2018-11-01T21:00:00.000-03:00"),
    "updateDate" : ISODate("2018-11-01T21:00:00.000-03:00")
}]

到目前为止我做了这个查询:

db.getCollection("project").aggregate([
    {
        $lookup: {
            from: "categories",
            localField: "categoryId",
            foreignField: "_id",
            as: "category"
        }
    },
    {
        $project: {
            id: 1,
            name: 1,
            categoryId: 1,
            inclusionDate: 1,
            updateDate: 1,
            categoryName: { $ifNull: [ "$category.name", "deleted" ] }
        }
    }
])

我只是不知道我做错了什么。在结果中,它从不返回类别名称,所有数据始终为空,而且我确信集合之间存在对应关系。我做错了什么?

mongodb lookup aggregation
1个回答
0
投票

问题是 categoryId 是 String,类别中的 _id 是 ObjectId 类型。所以我只需要转换就可以了。 最后,它看起来像这样:

db.getCollection("project").aggregate([
  {
    $lookup: {
      from: "categories",
      let: { categoryIdString: "$categoryId" },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [ "$_id", { $toObjectId: "$$categoryIdString" } ]
            }
          }
        }
      ],
      as: "category"
    }
  },
  {
    $addFields: {
      category: {
        $arrayElemAt: ["$category", 0]
      }
    }
  },
  {
    $project: {
      _id: 1,
      name: 1,
      inclusionDate: 1,
      updateDate: 1,
      categoryName: "$category.name"
    }
  }
])
© www.soinside.com 2019 - 2024. All rights reserved.