snovelli
snovelli

Reputation: 6058

Mongodb aggregation - count arrays with elements having integer value greater than

I need to write a MongoDB aggregation pipeline to count the objects having arrays containing two type of values:

This is my dataset:

[
 { values: [ 1, 2, 3] },
 { values: [12, 1, 3] },
 { values: [1, 21, 3] },
 { values: [1, 2, 29] },
 { values: [22, 9, 2] }
]

This would be the expected output

{
  has10s: 4,
  has20s: 3
}

Mongo's $in (aggregation) seems to be the tool for the job, except I can't get it to work.

This is my (non working) pipeline:

db.mytable.aggregate([
  {
    $project: {
      "has10s" : { 
         "$in": [ { "$gte" : [10, "$$CURRENT"]}, "$values"]} 
    },
     "has20s" : { 
         "$in": [ { "$gte" : [20, "$$CURRENT"]}, "$values"]} 
    }
  },
  { $group: { ... sum ... } }
])

The output of $in seems to be always true. Can anyone help?

Upvotes: 0

Views: 49

Answers (1)

Akrion
Akrion

Reputation: 18525

You can try something like this:

db.collection.aggregate([{
    $project: {
      _id: 0,
      has10: {
        $size: {
          $filter: {
            input: "$values",
            as: "item",
            cond: { $gte: [ "$$item", 10 ] }
          }
        }
      },
      has20: {
        $size: {
          $filter: {
            input: "$values",
            as: "item",
            cond: { $gte: [ "$$item", 20 ] }
          }
        }
      }
    }
  },
  {
    $group: {
      _id: 1,
      has10: { $sum: "$has10" },
      has20: { $sum: "$has20" }
    }
  }
])

Using $project with $filter to get the actual elements and then via $size to get the array length.

See it working here

Upvotes: 1

Related Questions