Search This Blog

Sunday 10 August 2014

Using query language with MongoDB

In the previous posts we have seen how to insert and read data from the MongoDB client and from the Java API. Now to fetch documents by executing queries on the collection.
We saw the find method that can be used to fetch records. The find method can be passed with query like parameters. At its simplest:
Here we have passed a parameter to the find method. The parameter - "{}" resembles an EMPTY JSON object. It is equivalent to the no parameter option - return all records in the collection. This parameter is known as the query document.
To query on specific fields, we can pass fields to the query document:
 Here we have queried on the name field by passing the query document {"name":"apple"}.
However what if we want to fetch multiple fruits? Or rather how to specify or conditions on the database ?
db.fruits.find( { name: { $in: [ 'mango', 'apple' ] } } )
In the above code we have used in operator to indicate an in condition - similar to the in keyword we use in SQL. In a normal SQL application we would have used the or condition.
There is a similar or operator available in MongoDB:
From the MongoDB Docs:
Syntax: { $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }
The $or operator performs a logical OR operation on an array of two or more 
<expressions> and selects the documents that satisfy at least one of the <expressions>.
The website also recommends when to use the operator:
use the $in operator rather than the $or operator when performing equality checks on 
the same field.
There is also a not in operator:
db.fruits.find( {name: {$nin: ['mango','apple']}} )
The result would be a complement of the records returned by our earlier in based query.
Specifying and conditions is easy in the query document. We simply keep adding more attributes:

No comments:

Post a Comment