Mongoose 可选存在于 mongoose 中的字段的聚合 - 评分计算

Mongoose Aggregation of a field that optionally exists in mongoose - rating calculation

我的产品文档是这样的:

{
  "_id": {
    "$oid": "60999af1160b0eebed51f203"
  },
  "name": "Olive Skin care On1",
  "business": {
    "$oid": "609fa1d25adc157a33c59098"
  },
    "ratings": [{
    "_id": {
      "$oid": "60bdb541d6212ec44e62273c"
    },
    "user": {
      "$oid": "5fdce4bd75dbe4864fcd5001"
    },
    "rating": 5
  }]
}

我有这个 mongoose 查询来获取产品详细信息和产品评级。有些产品有评级字段,而有些则没有。当我如此处所示进行查询时,它 return 是一个具有计算平均评分的预期响应。响应看起来是这样的:

[
  {
      "_id": "609a657f2bf43c290fb22df8",
      "name": "Olive babay Oil",
      "business": "6079ed084d9ab0c3171317ea",
      "averageRating": 5
  }
]

查询如下:

const productArray = await Product.aggregate([
    {
        $match: {
            _id: mongooseProductId,
        },
    },
    { $unwind: "$ratings" },
    {
        $project: {
            averageRating: { $avg: "$ratings.rating" },
            name: 1,
            business: 1,
        },
    },
]);

但是,如果通过删除评级字段修改上面的同一产品,下面的查询将 return 一个空数组。 我如何编写查询以确保评级字段是否存在,只要满足匹配条件,我就不会得到一个空数组。

这意味着当我的产品文档中不存在评级字段时,我可以获得这样的预期响应:

[
  {
      "_id": "609a657f2bf43c290fb22df8",
      "name": "Olive babay Oil",
      "business": "6079ed084d9ab0c3171317ea",
      "averageRating": null
  }
]

当评级字段存在时:

[
  {
      "_id": "609a657f2bf43c290fb22df8",
      "name": "Olive babay Oil",
      "business": "6079ed084d9ab0c3171317ea",
      "averageRating": 5
  }
]

基于@turivishal 的评论。下面的查询解决了这个问题。

const productArray = await Product.aggregate([
    {
        $match: {
            _id: mongooseProductId,
        },
    },
    { $unwind:{ path: "$ratings", preserveNullAndEmptyArrays: true } },
    {
        $project: {
            averageRating: { $avg: "$ratings.rating" },
            name: 1,
            business: 1,
        },
    },
]);