In MongoDB, how to search for documents by the size of an Array

0

I have a collection of documents that are nodes of a graph, where each node has its list of adjacencies:

{
'_id': ObjectId('547ce6f4ffaba82f360fc525'),
'adj': ['no_2'],
'nome': 'no_1'
}
{
'_id': ObjectId('547ce6f4ffaba82f360fc526'),
'adj': ['no_1', 'no_3'],
'nome': 'no_2'
}
{
'_id': ObjectId('547ce6f4ffaba82f360fc527'),
'adj': ['no_1'],
'nome': 'no_3'
}

I want to list all documents (nodes) where the size of array 'adj' is greater than or equal to an X value.

I tried to resolve using $ gt and $ size but both the $ size operator only returns by exact value when it does not seem possible to use the two operators together.

    
asked by anonymous 02.12.2014 / 01:19

1 answer

2

(1) I found a solution using $ where :

db.grafo.find( { $where: "this.adj.length > X" } );
The problem with this solution is that this strategy does not make use of indexes or any other strategy to make the search efficient: the $ where operator basically runs the operator for all the documents in the collection.

(2) A second strategy with more "NoSQL face" is to create a new field that stores the size of the array. This way you can index the value, but it is more a value to update when the array is modified.

(3) A third very interesting solution: ask if a given array position exists!

Y=X-1
db.grafo.find( { "adj.Y" : {"$exists": true} } );

OBS.1: I just do not know if there is any efficiency difference between (1) and (3). It seems to me that not.

NOTE: Both solution (1) and (3) are only possible in Mongo 2.2 +

    
02.12.2014 / 01:22