In: Computer Science
Using MongoDB, what command would you enter to retrieve this document using only the zip code 11242? db.inspections.find(???????) Database: city Collection: inspections {"_id":{"$oid":"56d61033a378eccde8a898ae"}, "id":"23536-2015-ENFO", "certificate_number":5373970, "business_name":"NZO CORP.", "date":"Apr 22 2015", "result":"Violation Issued", "sector":"Grocery-Retail - 808", "address":{"city":"BROOKLYN", "zip":11242, "street":"COURT ST", "number":26}}
Code:
db.inspections.find({ "address.zip": 11242})
This is a simple code. Now let us break down the query into simpler part.
Explanation of the
Query:
1) How we write a find command ?
2) The document in which you are using this function is know as embedded document. This approach always maintains the data which is related in a single document hence it is easy to retrieve and maintain the document. This approach is used in many-to-one relationship.
3) Hence to access the specific field in an embedded document we have to use a dot notation. We have to concatenate i.e. join the embedded document with a dot and the name of the field within the quotes.
4) So as we wanted zip which was inside embedded document i.e. address so we wrote address.zip. Here we used concatenation using the dot.
5) Now this was the selection of the variable which had to find. We have to find zip value 11242 so as the value is in integer we will not put quotes and the query will look like "address.zip": 11242.
Screenshot:
Database example:
Query:
Output:
Note: If you have any more query please comment. I will be ready to help you. Thanks.