MongoDB:在文档中计算的值上执行collection.find()。

3

假设我有一个包含以下文档的集合:

{
    "_id" : ObjectId("111e2133c57a1d6111111111"),
    "scores" : [ 
        {
            "date" : ISODate("2021-03-29T05:00:20.965Z"),
            "test 1 points" : 50,
            "test 2 points" : 10,
            "total possible points" : 100
        }
    ]
}

{
    "_id" : ObjectId("111e2133c57a1d6111111222"),
    "scores" : [ 
        {
            "date" : ISODate("2021-03-27T05:00:20.965Z"),
            "test 1 points" : 30,
            "test 2 points" : 20,
            "total possible points" : 200
        }
    ]
}

如果我想要查找所有满足 ("test 1 points" + "test 2 points") / "total possible points" 大于0.50 的文档,是否有一种有效的方法可以通过 MongoDB 的 find() 命令实现?

目前,我正在使用低效的方法,即循环遍历每个文档并执行计算,然后记录 ObjectId(文档ID),如果计算出的值大于0.50,则将其记录下来。

谢谢!

1个回答

1

演示 - https://mongoplayground.net/p/c19Xx9-Ahb-

$unwind 分数以获得单独的文档,使用 $add $divide$gtvalidEntry 设置为 true 或 false。

然后 $match 文档。

db.collection.aggregate([
  { $unwind: "$scores" },
  {
    $addFields: {
      validEntry: {
        $gt: [
          { $divide: [
              { $add: [ "$scores.test 1 points", "$scores.test 2 points" ] },
              "$scores.total possible points"
            ]
          },
        0.5]
      }
    }
  },
  { $match: { validEntry: true } }
])

如果你想要获取原始文档,$group它们并且通过_id将分数$push回数组中。

  {
    $group: { _id: "_id", scores: { $push: "$scores" } }
  }

https://mongoplayground.net/p/d8xhOHYV4kn


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接