Query a nested array in MongoDb

2019-07-04 19:33发布

问题:

I would like to retrieve documents by the presence of an string in a nested array. For example, the data (representing a dependency parse of a sentence) looks like:

{'tuples': [['xcomp', 'multiply', 'using'], 
            ['det', 'method', 'the'], 
            ['nn', 'method', 'foil'], 
            ['dobj', 'using', 'method']]}

The closest solution I've found assumes that ['nn', ...] is the second position of the tuples list-of-lists:

 db.c.find({'tuples.2.0' : 'nn'})

Is there a way to relax the fixed position? The tuples (not their contents) can be in any order.

Secondly, it would be really great to be able to retrieve documents that have ['nn', 'method', X], meaning a noun "method" in their dependency parse.

Thank you!

回答1:

Got it!

db.c.find({'tuples' : {$elemMatch : {$all : ['nn']}}})
db.c.find({'tuples' : {$elemMatch : {$all : ['nn','method']}}})