4

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

1
  • Starting in MongoDB 4.4, $where no longer supports the deprecated BSON type JavaScript with scope (i.e. BSON type 15). The use of JavaScript with scope for the $where function has been deprecated since version 4.2.1. Ref docs.mongodb.com/manual/reference/operator/query/where So when you upgrade your version,it wont work Commented Aug 24, 2020 at 5:25

4 Answers 4

8

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
    }
  }
})
Sign up to request clarification or add additional context in comments.

1 Comment

The query {type:{$gt:{$size:1}}} doesn't work: mongoplayground.net/p/HSuYFa848fX - it always returns 0 elements
0

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.

Comments

0

An alternative way to tackle the problem is to ask:

how can I find the document in MongoDB that has an element in the (n)-th position in the array field?

To achieve this, you can use the following query

{ "type.1": { $exists: true } }

this solution is cleaner and it does not require the use of aggregate pipelines

Comments

-1
  1. You can use $gt

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

  1. You can use $where

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

1 Comment

$gt to directly compare arrays to integers doesn't do what you may think it does. See "Type Bracketing" in the MongoDB manual. Generally - this kind of comparison will always return "false".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.