Richard John
Richard John

Reputation: 487

MongoDB aggregation pipeline: counting documents with a field is less than value?

I have an existing report using MongoDB's aggregation framework, and I'd like to add a new field to it - a count of all documents where one of the numeric fields is less than a given value.

My documents have a length field, which I'm already calculating the average of, so in addition to this I'd like the number of documents where it's lower than a certain number.

My current aggregation pipeline is very simple:

db.streams.aggregate([ 
  { $match: { track_id: "ecb96af4537d4263b83f5675dbcc0388" }},
  { $group: { _id: "$source", listens: { $sum: 1 } }   }
])

I've tried using $sum and $lt, but the count is always 0. I'm guessing this is because $sum only counts when 1 is returned, but $lt returns true. This is what I tried:

db.streams.aggregate([{
  $match: {
    track_id: "ecb96af4537d4263b83f5675dadd0388"
  }
}, {
  $group: {
    _id: "$source",
    listens: {
      $sum: 1
    },
    skips: {
      $sum: {
        $lt: ["$length", 1000]
      }
    }
  }
}, ])

Does anybody know how I can achieve this? Thank you!

Upvotes: 1

Views: 791

Answers (1)

DAXaholic
DAXaholic

Reputation: 35338

You could add a nested condition like so

...
skips: {
    $sum: {
        $cond: {
            if: { $lt: ["$length", 1000]},
            then: 1,
            else: 0
        }
    }
}
...

Upvotes: 0

Related Questions