Kyll
Kyll

Reputation: 7139

How to find a document with array size within a range in MongoDB?

Given the following document structure:

{
  _id : Mongo ID,
  data : [someData1, someData2, ..., someDataN]
}

I want to get all documents which data size is between a and b (strict positive integers, consider a < b is always true).
I first thought about using $size, but the Mongo doc states:

$size does not accept ranges of values. To select documents based on fields with different numbers of elements, create a counter field that you increment when you add elements to a field.

(Emphasis mine)

How to retrieve all the documents with a data array of length between a and b without using a counter?


Related but did not solve:

Upvotes: 3

Views: 1954

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You can use the $exists operator approach by including multiple terms in your query and building it up programmatically:

var startKey = 'data.' + (a-1);
var endKey = 'data.' + b;
var query = {};
query[startKey] = {$exists: true};
query[endKey] = {$exists: false};
db.test.find(query);

So for a=1 and b=3, for example, you end up with a query object that looks like:

{
    "data.0" : {
        "$exists" : true
    },
    "data.3" : {
        "$exists" : false
    }
}

The first part ensures there are at least a elements, and the second part ensures there are no more than b elements.

Upvotes: 5

Related Questions