The Wayback Machine - https://web.archive.org/web/20240703025709/https://www.geeksforgeeks.org/what-is-a-mongodb-query/
Open In App

What is a MongoDB Query?

Last Updated : 06 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB Query is a fundamental aspect of MongoDB that allows users to fetch data from the database. Similar to SQL queries in traditional databases, MongoDB queries provide simplicity and flexibility in retrieving specific data based on certain criteria or conditions.

In this article, We will learn about the MongoDB Query in detail by performing various Queries on document of MongoDB collection and so on.

MongoDB Query

  • MongoDB Query allows retrieving data from the MongoDB database. MongoDB Query provides simplicity in the 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 that can be used to retrieve specific data from the database. 
  • MongoDB provides the function names as db.collection_name.find() to operate query operations on the database. 

Set Up an Environment:

To understand MongoDB Query we need a collection called articles on which we will perform various operations and queries. Below are the sample documents which we will use in the article.

[
{
"_id": ObjectId("6009585d35cce6b7b8f087f1"),
"title": "Math",
"author": "Aditya",
"level": "basic",
"length": 230,
"example": 11
},
{
"_id": ObjectId("60095b8a3fc110f90873ce29"),
"title": "Array",
"author": "Aditya",
"level": "basic",
"length": 200,
"example": 5
},
{
"_id": ObjectId("60095b8a3fc110f90873ce2a"),
"title": "Stack",
"author": "Rakesh",
"level": "easy",
"length": 400,
"example": 10
},
{
"_id": ObjectId("60095b8a3fc110f90873ce2b"),
"title": "Queue",
"author": "Rakesh",
"level": "medium",
"length": 350,
"example": 2
},
{
"_id": ObjectId("60095b8a3fc110f90873ce2c"),
"title": "Tree",
"author": "devil",
"level": "high",
"length": 1000,
"example": 10
},
{
"_id": ObjectId("60095b8a3fc110f90873ce2d"),
"title": "Graph",
"author": "Aditya",
"level": "high",
"length": 1500,
"example": 15
},
{
"_id": ObjectId("60095b8d3fc110f90873ce2e"),
"title": "Segment Tree",
"author": "devil",
"level": "very high",
"length": 500,
"example": 20
},
{
"_id": ObjectId("60095fd4e5a7731b2a55a922"),
"title": "Trie",
"author": "Rakesh",
"length": 500,
"example": 20,
"time": 50
}
]

Select Single Documents in a Collection

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 ()

Example:

db.article.findOne()

Output:

test> db.article.findOne()
{
_id: ObjectId('6009585d35cce6b7b8f087f1'),
title: 'Math',
author: 'Aditya',
level: 'basic',
length: 230,
example: 11
}

Here, we are going to display the first document of the article collection.

Select All Documents in a Collection

Example:

Retrieve and display all documents from the article.

db.article.find().pretty() 

Output:

[
{
_id: ObjectId('6009585d35cce6b7b8f087f1'),
title: 'Math',
author: 'Aditya',
level: 'basic',
length: 230,
example: 11
},
{
_id: ObjectId('60095b8a3fc110f90873ce29'),
title: 'Array',
author: 'Aditya',
level: 'basic',
length: 200,
example: 5
},
{
_id: ObjectId('60095b8a3fc110f90873ce2a'),
title: 'Stack',
author: 'Rakesh',
level: 'easy',
length: 400,
example: 10
},
{
_id: ObjectId('60095b8a3fc110f90873ce2b'),
title: 'Queue',
author: 'Rakesh',
level: 'medium',
length: 350,
example: 2
},
{
_id: ObjectId('60095b8a3fc110f90873ce2c'),
title: 'Tree',
author: 'devil',
level: 'high',
length: 1000,
example: 10
},
{
_id: ObjectId('60095b8a3fc110f90873ce2d'),
title: 'Graph',
author: 'Aditya',
level: 'high',
length: 1500,
example: 15
},
{
_id: ObjectId('60095b8d3fc110f90873ce2e'),
title: 'Segment Tree',
author: 'devil',
level: 'very high',
length: 500,
example: 20
},
{
_id: ObjectId('60095fd4e5a7731b2a55a922'),
title: 'Trie',
author: 'Rakesh',
length: 500,
example: 20,
time: 50
}
]

In the above Query, We have display the documents of the article collection in a well-formatted way using pretty() method.

Specify Equality Condition 

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.

Example: 

Retrieve and display all documents from the ‘article’ collection where the author is “devil”.

db.article.find({author:{$eq:"devil"}}).pretty()  

Output:

[
{
_id: ObjectId('60095b8a3fc110f90873ce2c'),
title: 'Tree',
author: 'devil',
level: 'high',
length: 1000,
example: 10
},
{
_id: ObjectId('60095b8d3fc110f90873ce2e'),
title: 'Segment Tree',
author: 'devil',
level: 'very high',
length: 500,
example: 20
}
]

In the above Query, We have 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. 

Syntax:  

db.collection_name.find({< key > : {$gte : < value >}}) 
or 
db.collection_name.find({< key > : {$lte : < value >}}) 

Example: 

Retrieve and display all documents from the ‘article’ collection where the length is greater than or equal to 510.

db.article.find({length:{$gte:510}}).pretty()

Output:

[
{
_id: ObjectId('60095b8a3fc110f90873ce2c'),
title: 'Tree',
author: 'devil',
level: 'high',
length: 1000,
example: 10
},
{
_id: ObjectId('60095b8a3fc110f90873ce2d'),
title: 'Graph',
author: 'Aditya',
level: 'high',
length: 1500,
example: 15
}
]

In the above Query, We have 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.

Example:  

db.article.find({time:{$exists:"true"}}).pretty()

Output:

[
{
_id: ObjectId('60095fd4e5a7731b2a55a922'),
title: 'Trie',
author: 'Rakesh',
length: 500,
example: 20,
time: 50
}
]

In the above Query, We have documents which has the attribute named as time by passing a filter query that is {time : {$exists : “true”}} in the find() method.

Specify AND Conditions

$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.

Example:

db.article.find({$and:[{level:{$eq:"high"}},{level:{$exists : "true"}}]}).pretty()

Output:

[
{
_id: ObjectId('60095b8a3fc110f90873ce2c'),
title: 'Tree',
author: 'devil',
level: 'high',
length: 1000,
example: 10
},
{
_id: ObjectId('60095b8a3fc110f90873ce2d'),
title: 'Graph',
author: 'Aditya',
level: 'high',
length: 1500,
example: 15
}
]

In the above Query, We have 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”}} 

Specify AND as well as OR Conditions

Example: 

Retrieve articles that are either authored by “Aditya” and have a level of “basic”, or authored by “Rakesh” with a level of “medium”.

db.article.find({
$or: [
{ level: "basic", author: "Aditya" },
{ $and: [
{ level: "medium" },
{ author: "Rakesh" }
]
}
]
}).pretty()

Output:

[
{
_id: ObjectId('6009585d35cce6b7b8f087f1'),
title: 'Math',
author: 'Aditya',
level: 'basic',
length: 230,
example: 11
},
{
_id: ObjectId('60095b8a3fc110f90873ce29'),
title: 'Array',
author: 'Aditya',
level: 'basic',
length: 200,
example: 5
},
{
_id: ObjectId('60095b8a3fc110f90873ce2b'),
title: 'Queue',
author: 'Rakesh',
level: 'medium',
length: 350,
example: 2
}
]

Limit The Query

This query method specifies a maximum number of documents for a cursor to return. 

Example: 

db. article. find({author : "devil" }). limit(2) . pretty() 

Output : 

[
{
_id: ObjectId('60095b8a3fc110f90873ce2c'),
title: 'Tree',
author: 'devil',
level: 'high',
length: 1000,
example: 10
},
{
_id: ObjectId('60095b8d3fc110f90873ce2e'),
title: 'Segment Tree',
author: 'devil',
level: 'very high',
length: 500,
example: 20
}
]

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).

Conclusion

Overall, MongoDB queries are essential for interacting with MongoDB databases. By using the find() method and various query operators, users can retrieve specific documents that match their criteria. Whether it’s selecting single documents, filtering based on conditions, or combining multiple conditions using logical operators, MongoDB queries offer a powerful and efficient way to fetch data from MongoDB databases



Previous Article
Next Article

Similar Reads

MongoDB - Query Documents using Mongo Shell
MongoDB provides you read operations to retrieve documents from the collection or query a collection for a document. You can perform read operations using the db.collection.find() method. This method selects or views the documents from the collection and returns the cursor to the selected document. find() is a mongo shell method, which can be used
4 min read
MongoDB - Query Embedded Documents Using Mongo Shell
MongoDB provides you read operations to retrieve embedded/nested documents from the collection or query a collection for a embedded/nested document. You can perform read operations using the db.collection.find() method. This method selects or views embedded/nested documents of the collection and returns the cursor to the selected document. Syntax:
3 min read
MongoDB - Logical Query Operators
MongoDB supports logical query operators. These operators are used for filtering the data and getting precise results based on the given conditions. The following table contains the comparison query operators: Operator Description $and It is used to join query clauses with a logical AND and return all documents that match the given conditions of bo
2 min read
Python MongoDB - Update_many Query
MongoDB is a NoSQL database management system. Unlike MySQL the data in MongoDB is not stored as relations or tables. Data in mongoDB is stored as documents. Documents are Javascript/JSON like objects. More formally documents in MongoDB use BSON. PyMongo is a MongoDB API for python. It allows to read and write data from a MongoDB database using a p
3 min read
Specify Validation With Query Operators in MongoDB
MongoDB was released in February 2009. It is an open-source document-oriented database. It is classified as a NoSQL database. Its schema is dynamic and is unstructured language. It follows the CAP theorem (Consistency Availability and Partition tolerance). It provides horizontal scalability and high-performance data persistence. It solved the probl
4 min read
Query Modifiers in MongoDB
MongoDB was released in February 2009. It is an open-source document-oriented database and is classified as a NoSQL database. It follows the CAP theorem (Consistency Availability and Partition tolerance). It provides built-in support for the Sharding and replication. To ensure security MongoDB provides access control, authentication mechanism, and
6 min read
How to Query for Documents Where Array Size is Greater Than 1 in MongoDB
MongoDB's flexibility extends to handling arrays within documents, making it a powerful choice for data storage in modern applications. One common requirement is to find documents where an array field contains more than one element. In this article, We will various methods through which we can easily find the size of an array that is greater than 1
3 min read
How to Query MongoDB ObjectId by Date?
MongoDB ObjectId is an important element in document identification, but can it help us with date-based queries? Understanding the ObjectId's structure and its potential for querying by date opens up new possibilities for data retrieval and analysis. In this article, We will learn about how to perform query MongoDB ObjectId by date by understanding
4 min read
Date Query with ISODate in MongoDB doesn't Seem to Work
MongoDB's ability to handle date and time values efficiently is crucial for many applications. with the help of the ISODate function, developers can query data based on precise date and time criteria. However, mastering date queries with ISODate in MongoDB requires a deep understanding of its usage and drawbacks. In this article, we'll explore prac
3 min read
How to Query MongoDB with "like"?
Querying data in MongoDB often requires pattern-matching operations similar to SQL's "LIKE" operator. While MongoDB doesn't have a direct "LIKE" operator, it offers the $regex operator and regular expressions for achieving similar functionality. In this article, We will learn about How to Query MongoDB with "like" with the help of $regex and regula
3 min read
Article Tags :