Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to query child objects in mongodb

Tags:

mongodb

I'm new to mongodb and am trying to query child objects. I have a collection of States, and each State has child Cities. One of the Cities has a Name property that is null, which is causing errors in my app. How would I query the State collections to find child Cities that have a name == null?

like image 633
Justin Avatar asked Jan 21 '11 19:01

Justin


People also ask

How do I query a nested object in MongoDB?

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.

How do I search for an object in MongoDB?

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.

How do I query an array of objects in MongoDB?

Use the Array Index to Query for a Field in the Embedded Document. Using dot notation, you can specify query conditions for field in a document at a particular index or position of the array. The array uses zero-based indexing. When querying using dot notation, the field and index must be inside quotation marks.

How do I query embedded files in MongoDB?

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.


1 Answers

If it is exactly null (as opposed to not set):

db.states.find({"cities.name": null}) 

(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).

If it's the case that the property is not set:

db.states.find({"cities.name": {"$exists": false}}) 

I've tested the above with a collection created with these two inserts:

db.states.insert({"cities": [{name: "New York"}, {name: null}]}) db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]}) 

The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or query:

db.states.find({"$or": [   {"cities.name": null},    {"cities.name": {"$exists": false}} ]}) 
like image 141
Theo Avatar answered Sep 20 '22 16:09

Theo