MongoDB the method of querying according to the size of the array _mongodb

Source: Internet
Author: User
Tags documentation mongodb mongodb version

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}})

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.