node.js - Mongoose聚合管道: Comparing to own object

标签 node.js mongodb typescript mongodb-query aggregation-framework

我有一个示例 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.latedPersonId:userId

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

每当我在查询中输入该内容时,它都不会返回任何内容

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

最佳答案

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

使用$expr比较字段

阅读aggregation-expressions

$expr can build query expressions that compare fields from the same document in a $match stage. If the $match stage is part of a $lookup stage, $expr can compare fields using let variables. See Specify Multiple Join Conditions with $lookup for an example. $expr only uses indexes on the from the collection for equality matches in a $match stage. $expr does not support multikey indexes.

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

关于node.js - Mongoose聚合管道: Comparing to own object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66763493/

相关文章:

node.js - 使用ASAR构建后如何在 Electron 中运行命令行

javascript - 在node.js中使用axios通过post获取数据

mongodb - Spring数据mongodb中实体继承是如何实现的

typescript - 如何在不编写 Typescript 基类的情况下创建条件接口(interface)?

node.js - 我可以在 Typegoose 中使用私有(private)属性吗?

json - 如何使用Observable从文件中获取json数据

javascript - 将post数据获取到expressjs导致404服务器未找到

node.js - 如何自动将 intent 添加到 addRequestHandler

node.js - 如何使用 MongoDB Node 驱动程序通过 id 查找?

mongodb - 如何从 Heroku 中的 MongoHQ 下载生产数据到本地机器?