Query a nested array in MongoDb

2019-07-04 19:17发布

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条回答
迷人小祖宗
2楼-- · 2019-07-04 19:44

Got it!

db.c.find({'tuples' : {$elemMatch : {$all : ['nn']}}})
db.c.find({'tuples' : {$elemMatch : {$all : ['nn','method']}}})
查看更多
登录 后发表回答