我在MongoDB中有一系列文档(判断事件),如下所示:

{
    "_id" : ObjectId("5397a78ab87523acb46f56"),
    "inspector_id" : ObjectId("5397997a02b8751dc5a5e8b1"),
    "status" : 'defect',
    "utc_timestamp" : ISODate("2014-06-11T00:49:14.109Z")
}

{
    "_id" : ObjectId("5397a78ab87523acb46f57"),
    "inspector_id" : ObjectId("5397997a02b8751dc5a5e8b2"),
    "status" : 'ok',
    "utc_timestamp" : ISODate("2014-06-11T00:49:14.109Z")
}

我需要得到这样一个结果集:

[
  {
    "date" : "2014-06-11",
    "defect_rate" : '.92' 
  },  
  {
    "date" : "2014-06-11",
    "defect_rate" : '.84' 
  }, 
]

换句话说,我需要得到每天的平均缺陷率.这可能吗?

推荐答案

聚合框架就是您想要的:

db.collection.aggregate([
    { "$group": {
        "_id": {
            "year": { "$year": "$utc_timestamp" },
            "month": { "$month": "$utc_timestamp" },
            "day": { "$dayOfMonth": "$utc_timestamp" },
        },
        "defects": {
            "$sum": { "$cond": [
                { "$eq": [ "$status", "defect" ] },
                1,
                0
            ]}
        },
        "totalCount": { "$sum": 1 }
    }},
    { "$project": {
        "defect_rate": {
            "$cond": [
                { "$eq": [ "$defects", 0 ] },
                0,
                { "$divide": [ "$defects", "$totalCount" ] }
            ]
        }
    }}
])

因此,首先,你在当天使用date aggregation operators进行分组,得到给定日期的物品总数.这里使用$cond运算符确定"状态"是否实际上是缺陷,结果是仅计算"缺陷"值的条件$sum.

一旦每天对这些数据进行分组,你只需输入$divide,然后用$cond进行另一次判断,以确保你没有被零除.

Mongodb相关问答推荐

在服务器上部署后端时判断??=默认判断

如何通过 Go 以 UUID 类型保存 Mongo 中的内容?

如何在 MongoDB 中的集合下查找同一文档

MongoDB查询优化

使用golang中的过滤器从mongodb复合集合中获取所有数据

在 MongoDB 中,如何使用对当前值进行操作的函数来更新嵌套文档的值?

如何聚合过滤器嵌套文档并从其他字段中获取值

MongoDB查询仅返回嵌入文档

.insertOne 不是函数

使用 Spring Boot >= 2.0.1.RELEASE 将 ZonedDateTime 保存到 MongoDB 时出现 CodecConfigurationException

mongo php副本连接非常慢

如何在任意深度查找 MongoDB 字段名称

Mongodb 约定包

mongoose得到`TypeError: user.save is not a function` - 出了什么问题

指定在 mongodb .js 脚本中使用哪个数据库

Mongoose:查询starts with

通过 Java 执行 Mongo like Query (JSON)

MongoDB 按数组元素对文档进行排序

按 id 删除记录?

MongoDB - $set 更新或推送数组元素