MongoDB Query Document PDF
MongoDB Query Document PDF
In this chapter, we will learn how to query document from MongoDB collection.
Syntax
The basic syntax of find() method is as follows −
>db.COLLECTION_NAME.find()
Syntax
>db.mycol.find().pretty()
Example
>db.mycol.find().pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>
Apart from find() method, there is findOne() method, that returns only one document.
To query the document on the basis of some condition, you can use following operations.
AND in MongoDB
Syntax
In the find() method, if you pass multiple keys by separating them by ',' then MongoDB
treats it as AND condition. Following is the basic syntax of AND −
>db.mycol.find(
{
$and: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Example
Following example will show all the tutorials written by 'tutorials point' and whose title is
'MongoDB Overview'.
https://www.tutorialspoint.com/mongodb/mongodb_query_document.htm 2/4
2/28/2018 MongoDB Query Document
For the above given example, equivalent where clause will be ' where by = 'tutorials
point' AND title = 'MongoDB Overview' '. You can pass any number of key, value pairs
in find clause.
OR in MongoDB
Syntax
To query documents based on the OR condition, you need to use $or keyword. Following is
the basic syntax of OR −
>db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Example
Following example will show all the tutorials written by 'tutorials point' or whose title is
'MongoDB Overview'.
https://www.tutorialspoint.com/mongodb/mongodb_query_document.htm 3/4
2/28/2018 MongoDB Query Document
Advertisements
YouTube 52K
https://www.tutorialspoint.com/mongodb/mongodb_query_document.htm 4/4