The method of fetching or getting data from a MongoDB database is carried out by using queries. While performing a query operation, one can also use criteria or conditions which can be used to retrieve specific data from the database?
Querying the Records using find()
MongoDB provides a function called db.collection.find() which
is used for retrieval of documents from a MongoDB database.
The syntax for the
read operation is as follows:
db.collection.find(filter, projection)
·
filter: It is an
optional parameter. It specifies the selection filter with the help of query
operators.
·
projection: It
is an optional parameter. It specifies that only those fields return to the
document that matches the given query filter.
Here i cover different operations for
querying the data from the database:
1. retrieve all documents in a
collection
db.collection.find({});
2. retrieve documents in a collection
using a condition ( similar to WHERE in MYSQL )
db.collection.find({key: value});
Example:
db.studentdb.find({email:"manish@email.com"});
3. Display all Records without mention
any query.
db.collection.find({});
4.
Display First Record Only
db.studetdb.findOne()
db.studetdb.find()[0]
5.
Select documents that satisfy the given condition Using Query operators.
Syntax:
db.collection.find({field: {operator: value}})
In this section, we
are going to briefly discuss the below conditional operators.
· $eq: This operator fetch the documents from a collection that are
equal to the given value expression
· $gt: This operator fetch the documents from a collection that are
greater than the given value expression
· $gte: This operator fetch the documents from a collection that are
greater than or equal to the given value expression
· $lt: This operator fetch the documents from a collection that are
less than the given value expression
· $lte: This operator fetch the documents from a collection that are
less than or equal to the given value expression
· $in: This operator is used to get the documents where the value
of a field equals any value in the specified array.
· $nin: This operator is used to get the documents where the value of a field does not equals any value in the specified array.
To learn how to handle the different comparison
query operators provided by the Mongo database, let’s create a
collection inventory in warehouse database.
> use warehouse
Example-1.
> db.inventory.find( { qty: { $eq: 20 } } )
This command will only get those documents from the inventory collection where the value of the qty field equals the given value i.e. 20.
db.inventory.find( { qty: { $lt: 20 } } ) |
This command will only
get those documents from the inventory collection where the value of the qty field
is less than the given value i.e. 20.
Example-3.
db.inventory.find( { qty: { $in: [ 20, 25 ] } } )
This command will only get those documents from the inventory collection where
the value of the qty field value is either 20 or 25.
Logical Query operators
· $and: Joins query clauses with a logical
AND returns all documents that match the conditions of both clauses.
·
$not: Inverts the effect of a query
expression and returns documents that do not match the query expression.
·
$or: Joins query clauses with a logical OR returns all
documents that match the conditions of either clause.
·
$nor: Joins query clauses with a logical NOR
returns all documents that fail to match both clauses.
Let’s understand this with the help of an example.
Example-1
db.inventory.find( { $and: [ {"tags": "A"}, {"qty": 25} ] } )
This command will only
get those documents from the inventory collection where the value of the tags, qty field
matches the given values i.e. A and 25.
Example-2
db.inventory.find( { $or: [ {"tags": "A"}, {"qty": 20} ] } )
This command will only
get those documents from the inventory collection where the value of the tags, qty field
matches the given values i.e. A and 20.
Projection the Data
In MongoDB, projection means selecting only the
necessary data rather than selecting whole of the data of a document. If a
document has 5 fields and you need to show only 3, then select only 3 fields
from them.
MongoDB's find() method, explained in MongoDB Query
Document accepts second optional parameter that is list of
fields that you want to retrieve. In MongoDB, when you execute find() method,
then it displays all fields of a document. To limit this, you need to set a
list of fields with value 1 or 0. 1 is used to show the field while 0 is used
to hide the fields.
Syntax
The basic syntax of find() method
with projection is as follows −
db.COLLECTION_NAME.find({},{KEY:1})
Example:
db.inventory.find( {},{ _id:0, item:1, qty:1} )
This command will display
only those fields in documents from the inventory
collection where in the projection field’s value
set to 1 and by default _id field
will always display, so using projection filed set to 0 will also hide the _id
filed in the ouput data.
Limit the Records
To limit the records in
MongoDB, you need to use limit() method. The method accepts
one number type argument, which is the number of documents that you want to be
displayed.
Syntax
The
basic syntax of limit() method is as follows −
db.COLLECTION_NAME.find().limit(NUMBER)
Example
db.inventory.find().limit(2)
This command will display only 2 documents from the inventory collection because limit function limiting the number of records to display.
Skip() Method: Apart from limit() method, there is one more
method skip() which also accepts number type argument and
is used to skip the number of documents.
Syntax
The
basic syntax of skip() method
is as follows −
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
Example
db.inventory.find().limit(3).skip(1)
This command will skips
the first document in the database and then display next 3 documents only.
Sort the Records
To sort documents in
MongoDB, you need to use sort() method. The method accepts a
document containing a list of fields along with their sorting order. To specify
sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used
for descending order.
Syntax
The
basic syntax of sort() method is as follows −
db.COLLECTION_NAME.find().sort({KEY:1})
Example
db.inventory.find().sort({qty:1})
This method will sort the
document in ascending order based on qty
key field.
db.inventory.find().sort({qty:-1})
This method will sort the
document in descending order based on qty
key field.
NOTE: If you do not specify the sorting preference(i.e 1 or -1), then by default documents in a collection are sorted in ascending order.