Query and Write Operation Commands .css-134mg1q{-webkit-align-self:center;-ms-flex-item-align:center;align-self:center;padding:0 10px;visibility:hidden;} .css-6vrlzm{border-radius:0!important;display:initial!important;margin:initial!important;} .css-1l4s55v{margin-top:-175px;position:absolute;padding-bottom:2px;}
For details on a specific command, including syntax and examples, click on the link to the command's reference page.
- Coding Ground
- Corporate Training

- MongoDB Tutorial
- MongoDB - Home
- MongoDB - Overview
- MongoDB - Advantages
- MongoDB - Environment
- MongoDB - Data Modeling
- MongoDB - Create Database
- MongoDB - Drop Database
- MongoDB - Create Collection
- MongoDB - Drop Collection
- MongoDB - Data Types
- MongoDB - Insert Document

MongoDB - Query Document
- MongoDB - Update Document
- MongoDB - Delete Document
- MongoDB - Projection
- MongoDB - Limiting Records
- MongoDB - Sorting Records
- MongoDB - Indexing
- MongoDB - Aggregation
- MongoDB - Replication
- MongoDB - Sharding
- MongoDB - Create Backup
- MongoDB - Deployment
- MongoDB - Java
- MongoDB - PHP
- Advanced MongoDB
- MongoDB - Relationships
- MongoDB - Database References
- MongoDB - Covered Queries
- MongoDB - Analyzing Queries
- MongoDB - Atomic Operations
- MongoDB - Advanced Indexing
- MongoDB - Indexing Limitations
- MongoDB - ObjectId
- MongoDB - Map Reduce
- MongoDB - Text Search
- MongoDB - Regular Expression
- Working with Rockmongo
- MongoDB - GridFS
- MongoDB - Capped Collections
- Auto-Increment Sequence
- MongoDB Useful Resources
- MongoDB - Questions and Answers
- MongoDB - Quick Guide
- MongoDB - Useful Resources
- MongoDB - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
In this chapter, we will learn how to query document from MongoDB collection.
The find() Method
To query data from MongoDB collection, you need to use MongoDB's find() method.
The basic syntax of find() method is as follows −
find() method will display all the documents in a non-structured way.
Assume we have created a collection named mycol as −
And inserted 3 documents in it using the insert() method as shown below −
Following method retrieves all the documents in the collection −
The pretty() Method
To display the results in a formatted way, you can use pretty() method.
Following example retrieves all the documents from the collection named mycol and arranges them in an easy-to-read format.
The findOne() method
Apart from the find() method, there is findOne() method, that returns only one document.
Following example retrieves the document with title MongoDB Overview.
RDBMS Where Clause Equivalents in MongoDB
To query the document on the basis of some condition, you can use following operations.
AND in MongoDB
To query documents based on the AND condition, you need to use $and keyword. Following is the basic syntax of AND −
Following example will show all the tutorials written by 'tutorials point' and whose title is 'MongoDB Overview'.
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
To query documents based on the OR condition, you need to use $or keyword. Following is the basic syntax of OR −
Following example will show all the tutorials written by 'tutorials point' or whose title is 'MongoDB Overview'.
Using AND and OR Together
The following example will show the documents that have likes greater than 10 and whose title is either 'MongoDB Overview' or by is 'tutorials point'. Equivalent SQL where clause is 'where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')'
NOR in MongoDB
To query documents based on the NOT condition, you need to use $not keyword. Following is the basic syntax of NOT −
Assume we have inserted 3 documents in the collection empDetails as shown below −
Following example will retrieve the document(s) whose first name is not "Radhika" and last name is not "Christopher"
NOT in MongoDB
To query documents based on the NOT condition, you need to use $not keyword following is the basic syntax of NOT −
Following example will retrieve the document(s) whose age is not greater than 25
- Trending Now
- Data Structures
- DSA to Development
- Data Science
- Topic-wise Practice
- Machine Learning
- Competitive Programming
- Master Sheet
- Write an Interview Experience
- Share Your Campus Experience
- MongoDB Tutorial
Introduction
- How do Document Databases Work?
- How MongoDB works ?
- MongoDB: An introduction
- MongoDB: Getting Started
- What is MongoDB – Working and Features
- Difference between RDBMS and MongoDB
- MongoDB vs MySQL
Installation
- How to Install and Configure MongoDB in Ubuntu?
- How to install MongoDB on MacOS ?
- How to Install MongoDB on Windows?
Basics of MongoDB
- MongoDB – Database, Collection, and Document
- MongoDB Cursor
- DataTypes in MongoDB
- What is ObjectId in MongoDB
What is a MongoDB Query?
- MongoDB | Create Database using MongoShell
- MongoDB | Delete Database using MongoShell
- MongoDB CRUD operations
MongoDB Methods
- MongoDB Insert() Method – db.Collection.insert()
- MongoDB insertOne() Method – db.Collection.insertOne()
- MongoDB insertMany() Method – db.Collection.insertMany()
- MongoDB – Bulk.insert() Method
- MongoDB – db.collection.bulkWrite() Method
- MongoDB – Update() Method
- MongoDB updateOne() Method – db.Collection.updateOne()
- MongoDB updateMany() Method – db.Collection.updateMany()
- MongoDB – db.collection.Find() Method
- MongoDB – FindAndModify() Method
- MongoDB – FindOne() Method
- MongoDB – findOneAndDelete() Method
- MongoDB – db.collection.findOneAndReplace() Method
- MongoDB – db.collection.findOneAndUpdate() Method
- MongoDB – sort() Method
- MongoDB – copyTo() Method
- MongoDB count() Method – db.Collection.count()
- MongoDB – countDocuments() Method
- MongoDB – Drop Collection
- MongoDB Remove() Method – db.Collection.remove()
- MongoDB – db.collection.deleteone()
- MongoDB – Distinct() Method
- MongoDB – limit() Method
- MongoDB – skip() Method
- MongoDB | ObjectID() Function
- MongoDB – db.collection.CreateIndex() Method
- MongoDB – db.collection.createIndexes() Method
- MongoDB – getIndexes() Method
- MongoDB – dropIndex() Method
- MongoDB – dropIndexes() Method
Comparison Operators
- MongoDB – Comparison Query Operators
- MongoDB $cmp Operator
- MongoDB – Greater than Operator $gt
- MongoDB – Less than Operator $lt
- MongoDB – Equality Operator $eq
- MongoDB – Less than equals to Operator $lte
- MongoDB – Greater than equals to Operator $gte
- MongoDB – Inequality Operator $ne
- MongoDB $in Operator
- MongoDB – $nin Operator
Logical Operators
- MongoDB – Logical Query Operators
- MongoDB AND operator ( $and )
- MongoDB OR operator ( $or )
- MongoDB NOT operator ( $not )
- MongoDB NOR operator ( $nor )
Arithmetic Operators
- MongoDB $add Operator
- MongoDB $subtract Operator
- MongoDB $multiply Operator
- MongoDB $divide Operator
- MongoDB $abs operator
- MongoDB $floor Operator
- MongoDB $ceil Operator
- MongoDB $mod Operator
- MongoDB $sqrt Operator
- MongoDB $pow Operator
- MongoDB $exp Operator
- MongoDB $log Operator
- MongoDB $log10 Operator
- MongoDB $ln Operator
Field Update Operators
- MongoDB – Field Update Operators
- MongoDB – Maximum operator ( $max )
- MongoDB – Minimum operator ( $min )
- MongoDB – Increment Operator ( $inc )
- MongoDB – Multiply Operator ($mul)
- MongoDB – Rename Operator ($rename)
- MongoDB – Current Date Operator ($currentDate)
- MongoDB – SetOnInsert Operator ($setOnInsert)
- MongoDB Bitwise Update Operator
Array Expression Operators
- MongoDB $isArray Operator
- MongoDB $size Operator
- MongoDB $arrayElemAt Operator
- MongoDB $concatArrays Operator
- MongoDB $reverseArray Operator
Array Update Operators
- MongoDB – $pull Operator
- MongoDB – $pop Operator
- MongoDB – $pullAll Operator
- MongoDB – $push Operator
- MongoDB – Positional Operator ($)
- MongoDB – All Positional Operator ($[])
- MongoDB – $position Modifier
- MongoDB – $addToSet Operator
- MongoDB – $each Modifier
- MongoDB – $sort Modifier
- MongoDB – $slice Modifier

String Expression Operators
- MongoDB $concat Operator
- MongoDB $strcasecmp Operator
- MongoDB $toUpper Operator
- MongoDB $toLower Operator
- $substrCP (aggregation) operator in MongoDB
Working with Documents and Collections
- Defining, Creating and Dropping a MongoDB collection
- Adding and Querying the data in MongoDB
- How to Create Database & Collection in MongoDB?
- MongoDB – Query Documents using Mongo Shell
- MongoDB – Insert Single Document Using MongoShell
- MongoDB – Insert Multiple Document Using MongoShell
- MongoDB – Update Single Document Using MongoShell
- MongoDB – Update Multiple Documents Using MongoShell
- MongoDB – Replace Documents Using MongoShell
- MongoDB – Delete Single Document Using MongoShell
- MongoDB – Delete Multiple Documents Using MongoShell
- MongoDB – Check the existence of the fields in the specified collection
- Sorting Documents in MongoDB
- Capped Collections in MongoDB
- Create Relationship in MongoDB
- Search Text in MongoDB
- MongoDB – Map Reduce
- Upsert in MongoDB
- Indexing in MongoDB
- MongoDB – Index Types
- MongoDB – Compound Indexes
- MongoDB – Text Indexes
- MongoDB – Multikey Indexes
MongoDB Advance
- Export data from MongoDB
- Import data to MongoDB
- MongoDB – Regex
- MongoDB Projection
- MongoDB – Embedded Documents
- MongoDB – Query Embedded Documents Using Mongo Shell
- Aggregation in MongoDB
- How to Enable Authentication on MongoDB ?
- Create user and add role in MongoDB
- MongoDB – Replication and Sharding
- MongoDB – Backup and Restoration
MongoDB Applications and Projects
- Nodejs – Connect MongoDB with Node app using MongooseJS
- Signup Form Using Node.js and MongoDB
- Login form using Node.js and MongoDB
- Connect Django Project to MongoDB
MongoDB , the most popular open-source document-oriented database is a NoSQL type of database. NoSQL database stands for Non-Structured Query Database. MongoDB stores the data in the form of the structure(field:value pair) rather than tabular form. It stores data in BSON (Binary JSON) format just like JSON format.
A simple example of a MongoDB database collection.
{ “_id” : ObjectId(“6009585d35cce6b7b8f087f1”), “title” : “Math”, “author” : “Aditya”, “level” : “basic”, “length” : 230, “example” : 11 }
What is MongoDB Query?
MongoDB Query is a way to get the data from the MongoDB database. MongoDB queries provide the simplicity in process of fetching data from the database, it’s similar to SQL queries in SQL Database language. While performing a query operation, one can also use criteria or conditions which can be used to retrieve specific data from the database.
MongoDB provides the function names as db.collection_name.find() to operate query operation on database. In this post, we discussed this function in many ways using different methods and operators.
Here, we are working with:
Database: g eeksforgeeks Collection: Article
Note: Here “pretty()” query method is using for only better readability of Document Database.(It’s not necessary)
Field selection
The find() method displays the database collection in Non-Structured form({<Key> : <value>}) including auto-created <key> ” id ” by MongoDB and collection data inserted by user or admin.
db.collection_name.find()
Example:
This method is used to display all the documents present in the article collection.
Finding a single document
In MongoDB, we can find a single document using findOne() method, This method returns the first document that matches the given filter query expression.
Syntax:
db.collection_name.findOne ()
Here, we are going to display the first document of the article collection.
Displaying documents in a formatted way
In MongoDB, we can display documents of the specified collection in well-formatted way using pretty() method.
Syntax:
db.collection_name.find().pretty()
Here, we are going to display the documents of the article collection in a well-formatted way using pretty() method.
Equal filter query
The equality operator( $eq ) is used to match the documents where the value of the field is equal to the specified value. In other words, the $eq operator is used to specify the equality condition.
db.collection_name.find({< key > : {$eq : < value >}})
Here, we are going to display the documents that matches the filter query(i.e., {author : {$eq : “devil”}}) from the article collection.
Greater than filter query
To get the specific numeric data using conditions like greater than equal or less than equal use the $gte or $lte operator in the find() method.
db.collection_name.find({< key > : {$gte : < value >}}) or db.collection_name.find({< key > : {$lte : < value >}})
Here, we are querying to get documented data which has the length attribute value greater than 510. So, we pass a filter query that is {length : {$gte : 510}} in the find() method.
Check the existence filter query
$exists operator shows all the collection documents if they exist on a given key.
db.collection_name.find({< key > : {$exists : < boolean >}})
Example :
Here, we are going to look all the documents which has the attribute named as time by passing a filter query that is {time : {$exists : “true”}} in the find() method.
Logical operator query
$and operator comes under the type of MongoDB logical operator which perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression in the array.
Syntax :
db.collection_name.find({$and : [{< key > : {$eq : < value1 >}}, {< key > : {$exists : < boolean >}}]})
In this query example we are using and operator and given two condition which are highlighted following
- and operator: {$and : [ first condition, second condition]}
- first condition(level == “high”): { level : {$eq : “high”}}
- second condition: {level : {$exists : “true”}}
Project query
This query returned the result whatever we specify in parameter using 1 and 0
- 1: It indicated to return the result
- 0: It indicates to not return the result
These parameters called Projection Parameter .
db. collection_name. find({< key > : < value >}, {<key> : < Projection_Parameter >})
This query example is requesting the data which have the author as named “devil” but in the record don’t want to show the title attribute by specifying it as projection parameter 0
- Query to find a record having given attribute: { author : “devil”}
- Projection Parameter: {title : 0}
Limit Query
This query method specifies a maximum number of documents for a cursor to return.
Syntax :
db.collection_name.find({< key > : < value >}).limit(< Integer_value >)
db. article. find({author : “devil” }). limit(2) . pretty()
This query method is simply the extension of the find method only provide a result at a maximum limited number(here is 2)
- Query to find record having given attribute: find({author : “devil” })
- Query to limit result: limit( 2)
Output :
Sort the fields
In MongoDB, It returns the finding result in sorted order that can be ascending or descending. The order specifies by given parameter like
- 1 (Positive One): It indicates the Ascending order of having attribute value in the record.
- -1 (Negative One): It indicates the Descending order of having attribute value in the record.
db.collection_name.find(). sort({< key > : 1})
Example :
This Example will show the resultant record which has the example attribute and it will show in ascending order because here we are passing value 1.
- Query to finding record having given attribute: find ({author : “devil”})
- Query to sort parameter: sort({example : 1})
Please Login to comment...
Improve your coding skills with practice.
MongoDB Tutorial
Mongodb exercises, mongodb query api.
The MongoDB Query API is the way you will interact with your data.
The MongoDB Query API can be used two ways:
- CRUD Operations
- Aggregation Pipelines
MongoDB Query API Uses
You can use the MongoDB Query API to perform:
- Adhoc queries with mongosh , Compass, VS Code, or a MongoDB driver for the programming language you use.
- Data transformations using aggregation pipelines.
- Document join support to combine data from different collections.
- Graph and geospatial queries.
- Full-text search.
- Indexing to improve MongoDB query performance.
- Time series analysis.
Let's get started !

COLOR PICKER

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Top Tutorials
Top references, top examples, get certified.

IMAGES
VIDEO
COMMENTS
A database query is designed to retrieve specific results from a database. The query is formulated by the user following predefined formats. After searching through the data, information pertinent to the query is filtered out of the data co...
A query retrieves data from an Access database. Even though queries for Microsoft Access are written in Structured Query Language, it is not necessary to know SQL to create an Access query. The Query by Example screen allows users to run qu...
The primary option for executing a MySQL query from the command line is by using the MySQL command line tool. This program is typically located in the directory that MySQL has installed. You must have a username and password in order to con...
➤ Use the Select your language drop-down menu in the upper-right to set the language of the following examples.
For example, the following query always produces an error if $x is 0 :
The first is to use a logical AND conjunction to select documents in the collection matching all the conditions, or the logical OR to select
This query selects all documents in the inventory collection where the value of the quantity field is either 5 or 15.
Query and Write Operation Commands. Note. For details on a specific command, including syntax and examples, click on the link to the command's reference
To query data from MongoDB collection, you need to use MongoDB's find() method. Syntax. The basic syntax of find() method is as follows − >db.COLLECTION_NAME.
MongoDB aggregate pipeline syntax. This is an example of how to build an aggregation query: db.collectionName.aggregate(pipeline, options) ,.
How to Perform Basic Query Operations in MongoDB · > use myDB > db.createCollection("orders") · > use myDB >show collections orders system. · > db.orders. · > db.
In this video I am going to show you How to Query Documents In MongoDB. In this Tutorial we will learn. How to install MongoDB
MongoDB queries provide the simplicity in process of fetching data from the database, it's similar to SQL queries in SQL Database language.
Adhoc queries with mongosh , Compass, VS Code, or a MongoDB driver for the programming language you use. · Data transformations using aggregation pipelines.