【问题标题】:Count Array Elements Matching Condition计数数组元素匹配条件
【发布时间】:2018-06-12 20:00:51
【问题描述】:

我在 MongoDB 中有一个集合,它们的对象如下所示:

对象 1

{
    "_id" : ObjectId("5afde62a91952a2980a1b751"),   
    "notificationName" : "Teste Agendamento Pontual",
    "messages" : [ 
        {
            "timestamp" : ISODate("2018-05-17T20:29:33.045Z"),            
            "message" : "Teste Agendamento Pontual"
        }, 
        {
            "timestamp" : ISODate("2018-05-17T20:29:33.051Z"),            
            "message" : "Teste"
        }, 
        {
            "timestamp" : ISODate("2018-05-17T20:29:44.680Z"),            
            "message" : "OK"
        }        
    ]
}

对象 2

{
    "_id" : ObjectId("5afde62a9194322980a1b751"),   
    "notificationName" : "Teste Agendamento Pontual",
    "messages" : [ 
        {
            "timestamp" : ISODate("2018-05-17T20:29:33.045Z"),            
            "message" : "Teste Agendamento Pontual"
        }, 
        {
            "timestamp" : ISODate("2018-05-17T20:29:33.051Z"),            
            "message" : "NOT OK"
        }, 
        {
            "timestamp" : ISODate("2018-05-17T20:29:44.680Z"),            
            "message" : "asdsadasd"
        }        
    ]
}

...

我正在尝试获取按 notificationName 分组的结果,其中包含具有 OK 消息的对象计数和具有 NOT OK 消息的对象计数> 。 我想我需要在 $group 中创建一个 $cond 来检查 message 属性,但我不确定。并且不确定这是否是实现这一目标的最佳方式。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    如果您想匹配数组元素,那么您需要 $filter 并使用 $size 计算它们:

    db.collection.aggregate([
      { "$group": {
        "_id": "$notificationName",
        "countOk": {
          "$sum": {
            "$size": {
              "$filter": {
                "input": "$messages.message",
                "cond": { "$eq": [ "$$this", "OK" ] }
              }
            } 
          }
        }
      }}
    ])
    

    $filter 有它自己的cond 参数,这是一个逻辑条件,用于返回一个布尔值,确定数组元素是否匹配该条件并且可以返回。由于这只会返回来自message 的值数组,其中值是"OK",使用$eq 比较运算符进行测试,那么您使用$size“计数”结果数组成员。

    因为您正在“分组”,所以您使用$group 作为执行此操作的阶段,并且因为您正在“累积”您使用$sum 运算符来“累加”每个文档返回的所有$size 结果共享相同的分组键

    【讨论】:

      猜你喜欢
      • 2021-12-21
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 2023-02-24
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 2013-06-19
      相关资源
      最近更新 更多