简体   繁体   中英

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

db.collection.find({type: {$gt: 1}})

just change the name of the colletion


gt means greatter, you can see more about it here

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
    }
  }
})
  1. You can use $gt

db.collectionName.find({"type": {$gt: 1} });

  1. You can use $where

db.collectionName.find( { $where: "type > 1" } );

The only working solution for this problem is as follows:

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

All other solutions do not work. Tried it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM