Method for querying by array size under MongoDB

  • 2020-05-10 23:06:43
  • OfStack

Note: the mongodb version used by the author is 2.4.7.

First, insert the test data


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 key num corresponds to an array of values.

Query num for an array value with document of the specified size

The best way to do this is to use $size. For example, if you specify a size of 2, you can:

db.data.find({num:{$size:2}})

However, $size has one defect, that is, it cannot query the size of a certain range. For example, the following statement cannot run as expected:
db.data.find({num:{$size:{$gt:2}}}); // error 

The official documentation suggests that if you need to query the array size within a certain range, you can add an additional key to each document to save the current array size.

If the array size is some range

The first is to use $where. For example, if the array size is required to be less than 3:

db.data.find({ $where: "this.num.length < 3" })

This method has a lot of flexibility, but it is a bit slower.

Please refer to official document: about $where http: / / docs mongodb. org manual/reference/operator/query where /.

Another efficient method is to determine whether an element of a specified index exists in an array. For example, if the array size is required to be less than 3:

db.data.find({ "num.2": {$exists:0} })

If the array size is less than 3, num[2] does not exist.

If the array size is greater than 3, you can:

db.data.find({ "num.3": {$exists:1} })


Related articles: