【问题标题】:Mongodb filter query if sum of the array is greater than X如果数组的总和大于 X,MongoDB 过滤器查询
【发布时间】:2021-12-25 21:47:29
【问题描述】:

我正在尝试查找数组字段的总和,然后,想要过滤这些总和大于 100。

{
  name: 'John',
  grades: [60, 70, 40]     # sum of this array = 170 (take this)
},
{
  name: 'Doe',
  grades: [30, 20, 10]     # sum of this array = 60 (don't take this)
}

我对这个集合做了这样的投影:

db.collections.find({}, {
{
  sumOfGrades: { $sum: "$grades" }
})

// returns

{...sumOfGrades: 170}, {...sumOfGrades: 60}

// But I am trying to get the first doc(which is greater than 100) on mongoDB layer.

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    查询

    • 您可以通过简单的方式进行聚合
    • 求和,只有> 100通过匹配

    *过滤器是保留或不记录文件,项目是保留或不保留文件的一部分

    Test code here

    aggregate([{"$match":{"$expr":{"$gt":[{"$sum":"$grades"}, 100]}}}])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多