Home > Net >  Counting numbers greater than a certain number in an array in MongoDb
Counting numbers greater than a certain number in an array in MongoDb

Time:07-08

{
    "_id" : ObjectId(""),
    "CustomerId" : 13038,
    "AT" : ISODate("2021-12-01T04:00:00.000Z"),
    "dwell" : [ 
        7, 
        6, 
        12, 
        6     ]
},
{
    "_id" : ObjectId(""),
    "CustomerId" : 12036,
    "AT" : ISODate("2021-12-01T04:00:00.000Z"),
    "dwell" : [ 
        15, 
        3, 
        12
    ]
}

In these documents, I only want to get the count of the numbers in the dwell which are greater than 10.

For Example:

{"CustomerId": 13038, "Count": 1} //because only 12 bigger than 10
{"CustomerId": 12036, "Count": 2}

CodePudding user response:

You could do something like this using $size and $filter:

db.collection.aggregate([
  {
    $project: {
      _id: 0,
      CustomerId: 1,
      Count: {
        "$size": {
          "$filter": {
            "input": "$dwell",
            "as": "num",
            "cond": {
              $gt: [
                "$$num",
                10
              ]
            }
          }
        }
      }
    }
  }
])

Example MongoPlayground

  • Related