-1

I have a collection in MongoDB that contains an age column, is it possible to count the number of rows that have age column lower than for example 10, between 10 and 30 and upper than 30 in one query? i.e. output be something like this:

age             cnt
<=10            607
10< and < 30    304
>=30            405
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
badger
  • 2,908
  • 1
  • 13
  • 32
  • 1
    Post about [mongo group and count with condition](https://stackoverflow.com/questions/30169115/mongo-group-and-count-with-condition). Documentation on [$group](https://docs.mongodb.com/manual/reference/operator/aggregation/group/index.html). – prasad_ May 01 '20 at 09:16
  • 1
    Does this answer your question? [mongo group and count with condition](https://stackoverflow.com/questions/30169115/mongo-group-and-count-with-condition) making it a duplicate.. – whoami - fakeFaceTrueSoul May 01 '20 at 14:12

1 Answers1

2

(I post the answer may be helpful to someone!) As prasad_ said you can achieve this by using

db.getCollection("users").aggregate([
    {
        $project: {
            item: 1,
            lessThan10: {  
                $cond: [ { $lt: ["$dob.age", 10 ] }, 1, 0]
            },
            moreThan10lessThan30: {  
                $cond: [ { $and: [ { $gte: ["$dob.age", 10 ] }, { $lte: ["$dob.age", 30 ] } ] }, 1, 0]
            },
            morethan30:{
                $cond: [{ $gt: ["$dob.age", 30]}, 1, 0]
            }


        }
    },
    {
        $group: {
            _id: "$item",
            lessthan10: { $sum: "$lessThan10" },
            between10and30: { $sum: "$moreThan10lessThan30" },
            morethan30:{$sum:"$morethan30"}

        }
    }
])
badger
  • 2,908
  • 1
  • 13
  • 32