网站搜索

node.js - Mongoose 聚合管道:与自身对象比较


我有一个看起来像这样的 mongoose 对象示例:

  {
    _id: 5fa849ad4f6be0382363809c,
    ratings: {
      ratedPersonId: 7,
      rating: 7,
      timeSpent: 30,
      timestamp: 78,
      userThreshold: 5
    }
  },

它包含一个 _id 和一个评分列表,该列表是一个具有以下特征的子文档。

我创建了一个这样的聚合管道:

    const ratedUser = await this.ratingModel
      .aggregate([
        { $project: { ratings: 1 } },
        { $unwind: '$ratings' },
        {
          $match: {
            $and: [{ 'ratings.ratedPersonId': userId }, { 'ratings.rating': { $gte: 5 } }],
          },
        },
      ])
      .exec()

这适用于第一个条件 ratings.ratedPersonId: userId

我的问题是,我的第二个条件是评级应该大于或等于同一对象中的 userThreshold 字段。

每当我在查询中输入那个时,它就什么也不返回

 $and: [{ 'ratings.ratedPersonId': userId }, { 'ratings.rating': { $gte: 'ratings.threshold'} }],

答案#1

演示 - https://mongoplayground.net/p/AQMsJGkoFcu

使用 $expr 比较字段

阅读聚合表达式

$expr 可以在 $match 阶段构建比较同一文档中字段的查询表达式。如果 $match 阶段是 $lookup 阶段的一部分,$expr 可以使用 let 变量比较字段。有关示例,请参见使用 $lookup 指定多个连接条件。$expr 仅在 $match 阶段的等值匹配中使用集合中的索引。$expr 不支持多键索引。

db.collection.aggregate([
  {
    $project: {
      ratings: 1
    }
  },
  {
    $unwind: "$ratings"
  },
  {
    $match: {
      $and: [
        {
          "ratings.ratedPersonId": 7
        },
        {
          $expr: {
            $gte: [
              "$ratings.rating",
              "$ratings.userThreshold"
            ]
          }
        }
      ],
      
    },
  },
])