> 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("4daf2ccd697ebaacb10976ec"), "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.
Query on Nested Field To specify a query condition on fields in an embedded/nested document, use dot notation ( "field. nestedField" ). When querying using dot notation, the field and nested field must be inside quotation marks.
Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. If you specify only a single <query> condition in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch , $elemMatch can be omitted.
To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object. Here is the query to search in an array of objects in MongoDB.
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.
db.test.find({'a.b.c.d1' : 'e1'})
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With