Reading documents
To apply special value filters, we can pass specific values ββto the find() . Here is the SQL query:
SELECT * FROM Table1 WHERE name = 'ABC'
which is equivalent to the following in MongoDB ( Collection1 notification for Table1 ):
db.Collection1.find({name: 'ABC'})
We can bind count() to get the number of results, pretty() to get a readable result. The results can be further narrowed by adding additional parameters:
db.Collection1.find({name: 'ABC', rollNo: 5})
It is important to note that these filters are AND by default. To apply an OR filter, we need to use $or . These filters will be specified depending on the structure of the document. Example: for the attribute of the name object for the school object, we need to specify a filter, for example, "school.name" = 'AUHS'
We use the DOT notation here, trying to access the nested name field of the school field. Also note that filters are quoted , without which we get syntax errors.
You can match equality over arrays:
- on all arrays
- based on any item
- based on a specific item
- more complex matches using operators
In the following query:
db.Collection1.find({name: ['ABC','XYZ']})
MongoDB is going to identify documents by exact matching an array of one or more values. Now, for these types of queries, the order of the elements is important, which means that we will only match documents that ABC follow on XYZ , and these are only 2 elements of the name array
{name:["ABC","GHI","XYZ"]}, {name:["DEF","ABC","XYZ"]}
In the above document, we say that we need to get all the documents, where ABC is the first element. So, we will use the filter below:
db.Schools.find({'name.0': 'ABC' })