Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the document in mongodb where array size is greater than 1

I want to find all the documents which are present and have array size greater than 1

My MongoDB collection looks like

{
  "_id" : ObjectId("5eaaeedd00101108e1123452"),
  "type" : ["admin","teacher","student"]
}
{
  "_id" : ObjectId("5eaaeedd00101108e1123453"),
  "type" : ["student"], 
}

How I find the document which has more than 1 type

like image 789
Ronie Avatar asked Oct 27 '25 17:10

Ronie


1 Answers

You can do something like this. This is working version > 4.2

db.collection.find({
      $expr: {
        $gt: [
          {
            $size: "$type"
          },
          1
        ]
      }
    })

Working Mongo playground

If you use less, you can do something like follwoing

db.collection.find({
  type: {
    $gt: {
      $size: 1
    }
  }
})
like image 77
varman Avatar answered Oct 30 '25 07:10

varman