Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Query for documents where array size is greater than 1 in MongoDB?
There are multiple ways to query documents where an array field has more than a certain number of elements in MongoDB. The recommended approaches are $expr with $size, or the dot notation trick with $exists.
Sample Data
db.students.insertMany([
{"StudentName": "Larry", "Subjects": ["Java", "C", "C++"]},
{"StudentName": "Maxwell", "Subjects": ["MongoDB"]},
{"StudentName": "Carol", "Subjects": ["MySQL", "SQL Server", "PL/SQL"]}
]);
Method 1: Using $expr with $size (Recommended)
db.students.find({
$expr: { $gt: [{ $size: "$Subjects" }, 1] }
}).pretty();
{ "StudentName": "Larry", "Subjects": ["Java", "C", "C++"] }
{ "StudentName": "Carol", "Subjects": ["MySQL", "SQL Server", "PL/SQL"] }
Maxwell's document (1 subject) is excluded because the array size is not greater than 1.
Method 2: Using Dot Notation with $exists
Check if the element at index 1 (second element) exists ?
db.students.find({
"Subjects.1": { $exists: true }
}).pretty();
This returns documents where the array has at least 2 elements (index 1 exists).
Method 3: Using $where (Slower)
db.students.find({
$where: "this.Subjects.length > 1"
}).pretty();
Note: $where executes JavaScript and is slower than native operators. Avoid for large collections.
Comparison
| Method | Performance | MongoDB Version |
|---|---|---|
$expr + $size
|
Fast (native) | 3.6+ |
Dot notation .1 + $exists
|
Fast (uses index) | All versions |
$where |
Slow (JavaScript execution) | All versions |
Conclusion
Use $expr with $size for flexible array length comparisons (MongoDB 3.6+). The dot notation trick ("array.N": {$exists: true}) is the fastest and works on all versions. Avoid $where for performance-critical queries.
