MongoDB query help: $elemMatch in nested objects
> db.test.insert({"a" : { "b" : { "c" : { "d1" : [ "e1" ],
"d2" : [ "e2" ],
"d3" : [ "e3", "e4" ],
"d4" : [ "e5", "e6" ] } } } })
> db.test.find({'a.b.c' : {$exists : true}})
{ "_id" : ObjectId("4da开发者_Python百科f2ccd697ebaacb10976ec"), "a" : { "b" : { "c" : { "d1" : [ "e1" ], "d2" : [ "e2" ], "d3" : [ "e3", "e4" ], "d4" : [ "e5", "e6" ] } } } }
But none of these work:
> db.test.find({'a.b': "c"})
> db.test.find({'a.b': {$elemMatch : {"c" : {$exists: true}}}})
> db.test.find({'a.b': {$elemMatch : {$elemMatch : {$all : ["e1"] }}}})
Suppose I don't know what the values of c
and d1
...d4
are. Is there a generic way to search the nested-objects' structure for particular values?
I thought that was what $elemMatch
was for.
Thank you.
I thought that was what $elemMatch was for...
From the docs: Using the $elemMatch query operator, you can match an entire document within an array.
This does not sounds like what you're looking for.
Is there a generic way to search the nested-objects' structure for particular values?
It sounds like you want to search "everything in object 'c' for an instance of 'e1'".
MongoDB supports two related features, but the features not quite what you're looking for.
- Reach into objects, dot notation:
db.test.find({'a.b.c.d1' : 'e1'})
- Read through arrays: `db.test.find({'a.b.c.d4' : 'e5'})
It sounds like you're looking for the ability to do both at the same time. You want to "reach into objects" and "read through arrays" in the same query.
Unfortunately, I do not know of such a feature. You may want to file a feature request for this.
I believe the query you're looking for is
db.test.find({ 'a.b.c': { '$exists': true } });
To your credit, you were very close!
精彩评论