How to find count in mongodb using $in and using greater than and lesser than?

Viewed 339

i have document in Test collection as given below:

{
    "_id" : "3233123123213123123",
    "sequence":30,
    "containIds":["fgx"]
}
{
    "_id" : "534545345345345345",
    "sequence":70,
    "containIds":["abc", "fgx"]
}
{
    "_id" : "56756676767676767",
    "sequence":160,
    "containIds":[]
}
db.getCollection('Test').find({"containIds":{$in: [ "fgx", "containIds" ]}}).count(); // result 1

and 

db.getCollection(Test').count({sequence:{ $gt :  0, $lt : 99}})//result 2

but i want to combine both query in one and need to get a result. //result should be 1

do i need to aggregate and project? how to write query for both using $in and ($gt and $lt) in mongodb?

1 Answers

You can try aggregate() method and $facet stage to separate both query and result,

  • first, you can change the name, put your match criteria and $count to get total records
  • second, you can change the name, put your match criteria and $count to get total records
db.getCollection('Test').aggregate([
  {
    $facet: {
      first: [
        { $match: { "containIds": { $in: ["fgx", "containIds"] } } },
        { $count: "count" }
      ],
      second: [
        { $match: { sequence: { $gt: 0, $lt: 99 } } },
        { $count: "count" }
      ]
    }
  }
])

Playground

Related