Note: The MongoDB version used by the author is 2.4.7.
First insert test data
Copy Code code as follows:
Db.data.insert ({name: ' A ', num:[12,123,22,34,1]});
Db.data.insert ({name: ' B ', num:[42,22]});
Db.data.insert ({name: ' C ', num:[49]});
The value of the key num is an array.
Query num array value has a specified size of document
The best approach is to use $size, such as specifying a size of 2, to:
Copy Code code as follows:
Db.data.find ({num:{$size: 2}})
However, there is a flaw in $size that it is impossible to query the size of a range, for example, the following statement cannot be run as expected:
Copy Code code as follows:
Db.data.find ({num:{$size: {$gt: 2}}}); Error
The official documentation suggests that if the size of the array you want to query is within a range, you can also add a key to each document to hold the current array size.
If the size of the array is a range
In the other two ways, the first idea is to use $where, for example, if the size of the array is less than 3:
Copy Code code as follows:
Db.data.find ({$where: "This.num.length < 3"})
This approach has a lot of flexibility, but it's slower.
For $where, please refer to the official documentation: Http://docs.mongodb.org/manual/reference/operator/query/where/.
Another more efficient method is to determine whether an element of a specified index in an array exists, for example, if the size of the array is less than 3:
Copy Code code as follows:
Db.data.find ({"num.2": {$exists: 0}})
An array size of less than 3 means that num[2] does not exist.
If you require an array size greater than 3, you can:
Copy Code code as follows:
Db.data.find ({"num.3": {$exists: 1}})