English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Query Document in MongoDB

In this chapter, we will learn how to query documents from MongoDB collections.

find() method

To query data from a MongoDB collection, you need to use MongoDB'sfind()method.

Grammar

find()The basic syntax of the method is as follows-

> db.COLLECTION_NAME.find()

find() The method will display all documents in a non-structured manner.

Online Example

Assuming we have created a collection named mycol-

> use sampleDB
switched to db sampleDB
> db.createCollection("mycol")
{ "ok": :}} 1 }
>

and use the insert() method to insert into it3documents, as shown below-

> db.mycol.insert([
	{
		title: "MongoDB Overview",
		description: "MongoDB is not a SQL database",
		by: "Basic Tutorial",
		url: "http://www.oldtoolbag.com",
		tags: ["mongodb", "database", "NoSQL"],
		likes: 100
	},
	{
		title: "NoSQL Database",
		description: "NoSQL databases do not have tables",
		by: "Basic Tutorial",
		url: "http://www.oldtoolbag.com",
		tags: ["mongodb", "database", "NoSQL"],
		likes: 20,
		comments: [
			{
				user: "user1",
				message: "My first comment",
				dateCreated: new Date(",2013,11,10,2,35),
				like: 0
			}
		]
	}
])

The following methods retrieve all documents in the collection-

> db.mycol.find()
{ "_id": ObjectId("5dd4e2cc0821d3b44607534c"), "title": "MongoDB Overview", "description": "MongoDB is not a SQL database", "by": "Basic Tutorial", "url": "http://www.oldtoolbag.com", "tags": [ "mongodb", "database", "NoSQL" ], "likes": 100 }
{ "_id": ObjectId("5dd4e2cc0821d3b44607534d"), "title": "NoSQL Database", "description": "NoSQL databases do not have tables", "by": "Basic Tutorial", "url": "http://www.oldtoolbag.com", "tags": [ "mongodb", "database", "NoSQL" ], "likes": 20, "comments": [ { "user": "user1", "message": "My first comment", "dateCreated": ISODate("2013-12-09T21:05:00Z"), "like": 0 } ]}
>

pretty() method

To display the results in a formatted way, you can use the pretty() method.

Grammar

> db.COLLECTION_NAME.find().pretty()

Online Example

The following example retrieves all documents from a collection named mycol and displays them in a readable format.

> db.mycol.find().pretty()
{
	"_id" : ObjectId("5dd4e2cc0821d3b44607534c"),
	"title": "MongoDB Overview",
	"description": "MongoDB is not a SQL database",
	"by": "basic tutorial",
	"url" : "http://www.oldtoolbag.com",
	"tags": [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes": 100
}
{
	"_id" : ObjectId("5dd4e2cc0821d3b44607534d"),
	"title": "NoSQL Database",
	"description" : "NoSQL databases do not have tables"
	"by": "basic tutorial",
	"url" : "http://www.oldtoolbag.com",
	"tags": [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes": 20,
	"comments" : [
		{
			"user" : "user1",
			"message" : "My first comment",
			"dateCreated" : ISODate("2013-12-09T21:05:00Z"),
			"like" : 0
		}
	]
}

findOne() method

In addition to the find() method, there is also afindOne()The method returns only one document.

Grammar

>db.COLLECTIONNAME.findOne()

Online Example

The following example retrieves the document with the title MongoDB Overview.

> db.mycol.findOne({title: "MongoDB Overview"})
{
	"_id" : ObjectId("5dd6542170fb13eec3963bf0"),
	"title": "MongoDB Overview",
	"description": "MongoDB is not a SQL database",
	"by": "basic tutorial",
	"url" : "http://www.oldtoolbag.com",
	"tags": [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes": 100
}

Comparison of MongoDB's WHERE statement with RDBMS

To query documents based on certain conditions, you can use the following operations.

OperationFormatExampleSimilar statements in RDBMS
Equal to{<key>:<value>}db.col.find({"by":"Basic Tutorial"}).pretty()where by = 'Basic Tutorial'
Less than{<key>:{$lt:<value>}}db.col.find({"likes":{$lt:50}).pretty()where likes < 50
Less than or equal to{<key>:{$lte:<value>}}db.col.find({"likes":{$lte:50}).pretty()where likes <= 50
Greater than{<key>:{$gt:<value>}}db.col.find({"likes":{$gt:50}).pretty()where likes > 50
Greater than or equal to{<key>:{$gte:<value>}}db.col.find({"likes":{$gte:50}).pretty()where likes >= 50
Not equal to{<key>:{$ne:<value>}}db.col.find({"likes":{$ne:50}).pretty()where likes != 50
The value is in the array{<key>:{$in:[<value1>, <value2>,……<valueN>]db.mycol.find({"name":{$in:["Raj", "Ram", "Raghu"]}}).pretty()where name matches any of the values in :["Raj", "Ram", "Raghu"]
value is not in the array{<key>:{$nin:<value>}}db.mycol.find({"name":{$nin:["Ramu", "Raghav"]}}).pretty()name value is not in the array :["Ramu", "Raghav"] or does not exist at all

MongoDB AND condition

Grammar

To query documents based on the "AND" condition, you need to use the $and keyword. The basic syntax of AND is as follows-

>db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>}]})

Example

The following example will display all tutorials written by "basic tutorial" and with the title "MongoDB Overview".

> db.mycol.find({$and:[{"by":"basic tutorial"},{"title": "MongoDB Overview"}]}).pretty()
{
	"_id" : ObjectId("5dd4e2cc0821d3b44607534c"),
	"title": "MongoDB Overview",
	"description": "MongoDB is not a SQL database",
	"by": "basic tutorial",
	"url": "https://www.oldtoolbag.com",
	"tags": [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes": 100
}
>

For the example given above, the equivalent where clause will be' where by = 'basic tutorial' AND title = 'MongoDB Overview' '. You can pass any number of key-value pairs in the find clause.

MongoDB OR condition

Grammar

To query documents based on the "OR" condition, you need to use$orkeyword. The following isORBasic Syntax:

>db.mycol.find(
   {
      $or: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()

Example

The following example will display all tutorials written by "tutorials point" or with the title "MongoDB Overview".

>db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is not a SQL database",
   "by": "Basic Tutorial",
   "url": "http://www.oldtoolbag.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>

MongoDB AND and OR are used together

Online Example

The following example will display documents where likes are greater than10documents with likes greater than and the title is 'MongoDB Overview' or by is 'Basic Tutorial'. Equivalent to SQL WHERE clause 'where likes>10 AND (by = '基础教程' OR title = 'MongoDB概述')

>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"},
   {"title": "MongoDB Overview"}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is not a SQL database",
   "by": "Basic Tutorial",
   "url": "http://www.oldtoolbag.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>

MongoDB NOR condition

Grammar

To query documents using NOR conditions, the $nor keyword must be used. Below isNORBasic Syntax:

> db.COLLECTION_NAME.find(
	{
		$nor: [
			{key1: value1}, {key2:value2}
		]
	}
)

Example

Assuming we are in the collection empDetails were inserted into3documents, as shown below-

db.empDetails.insertMany(
	[
		{
			First_Name: "Radhika",
			Last_Name: "Sharma",
			Age: "26",
			e_mail: "[email protected]",
			phone: "9000012345"
		},
		{
			First_Name: "Rachel",
			Last_Name: "Christopher",
			Age: "27",
			e_mail: "[email protected]",
			phone: "9000054321"
		},
		{
			First_Name: "Fathima",
			Last_Name: "Sheik",
			Age: "24",
			e_mail: "[email protected]",
			phone: "9000054321"
		}
	]
)

The following example retrieves documents where the name is not "Radhika" and the name is also not "Christopher"

> db.empDetails.find(
	{
		$nor:[
			40
			{"First_Name": "Radhika"},
			{"Last_Name": "Christopher"}
		]
	}
).pretty()
{
	"_id" : ObjectId("5dd631f270fb13eec3963bef"),
	"First_Name" : "Fathima",
	"Last_Name" : "Sheik",
	"Age" : "24",
	"e_mail" : "[email protected]",
	"phone" : "9000054321"
}

MongoDB NOT condition

Grammar

To query documents based on NOT condition, you need to use the $not keyword, as follows}}NOTBasic Syntax:

> db.COLLECTION_NAME.find(
	{
		$NOT: [
			{key1: value1}, {key2:value2}
		]
	}
).pretty()

Online Example

The following example will retrieve documents whose age is not more than25years old documents

> db.empDetails.find({ "Age": { $not: { $gt: "25"} } }"
{
	"_id" : ObjectId("5dd6636870fb13eec3963bf7")
	"First_Name" : "Fathima",
	"Last_Name" : "Sheik",
	"Age" : "24",
	"e_mail" : "[email protected]",
	"phone" : "9000054321"
}