Open In App

What is a MongoDB Query?

Last Updated : 27 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

A MongoDB query is a request to the database to retrieve specific documents or data based on certain conditions or criteria. It is similar to SQL queries in traditional relational databases, but MongoDB queries are written using JavaScript-like syntax. The most common query operation in MongoDB is the find() method, which allows users to fetch documents from a collection that match the given query criteria.

In this article, we will walk you through the basics of MongoDB queries, explain how they work, and showcase advanced techniques for effective querying. Whether we are a beginner or an experienced developer, this comprehensive guide will help you understand the key concepts of MongoDB queries and how to use them in real-world applications.

How to Run a MongoDB Query?

To run a MongoDB query, you use the db.collection_name.find() function. You can specify criteria (conditions) within the find() method to filter documents based on field values. MongoDB supports a wide range of query operators to create complex queries, such as $eq, $gte, $lte, $in, $or, $and, and more.

Basic MongoDB Query Example:

db.collection_name.find({ field: value })

Example:

This query will retrieve all documents from the articles collection where the author field is equal to “Aditya”.

db.articles.find({ author: "Aditya" })

What Does a MongoDB Query Return?

A MongoDB query returns a cursor object that points to the documents that match the query conditions. The cursor can be iterated over to access each document. You can also use the .pretty() method to format the output in a readable way. If no matching documents are found, the query will return an empty result.

Setting Up the Environment

Before we dive into various MongoDB query examples, let’s set up a collection named articles to practice different query operations. Below is a sample of the documents in the articles collection:

Query:

[
{
"_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
}
]

Basic Query Operations

Basic query operations in MongoDB allow you to retrieve data from collections using simple conditions. These operations include retrieving all documents, filtering by specific field values, and limiting the number of results returned.

1. Select Single Documents in a Collection

To select a single document in MongoDB, the findOne() method is used. It searches for a document that matches the given filter criteria and returns the first document that meets the condition. If no document matches the query, it returns null. This is useful when you want to retrieve a specific document, like finding a user by their unique identifier or looking up a product by its ID.

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
}

Explanation: Here, we are going to display the first document of the article collection where the author is “Aditya”.

2. Select All Documents in a Collection

To retrieve all documents from a collection in MongoDB, the find() method is used. This method returns a cursor that iterates through all documents in the collection. By default, find() will return all documents without any filters, but you can add conditions to limit the results. You can also use .pretty() to format the output for better readability.

Example:

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
}
]

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

3. Filter Documents with 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
}
]

Explanation: In the above Query, We have display the documents that matches the filter query(i.e., {author  :  {$eq : “devil”}}) from the article collection.

4. Filter Documents with Greater Than or Less Than Condition 

To filter documents based on numeric conditions, such as greater than or less than, you can use the $gte (greater than or equal) and $lte (less than or equal) operators within the find() method. These operators allow you to retrieve documents that meet specific criteria based on numeric values.

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
}
]

Explanation: 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.

5. Check the Existence of a Field

The $exists operator in MongoDB is used to check whether a specific field exists in the documents of a collection. This operator helps filter documents that either have or do not have a particular field, providing more flexibility in queries.

Example:  

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

Output:

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

Explanation: 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.

Advanced MongoDB Query Techniques

1. 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.articles.find({
$and: [
{ author: "Aditya" },
{ level: "basic" }
]
}).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
}
]

Explanation: 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”}} 

2. Specify AND as well as OR Conditions

In MongoDB, the $and and $or operators are used to combine multiple conditions in a query, allowing more complex filtering.

  • $and: Combines multiple conditions, and documents must satisfy all conditions to be returned.
  • $or: Combines multiple conditions, and documents must satisfy at least one condition to be returned.

Example: 

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
}
]

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

3. Use OR Conditions

The $or operator in MongoDB is used to retrieve documents that match any of the specified conditions. It is helpful when you need to match multiple conditions and retrieve documents that meet at least one of them.

Example:

db.articles.find({
$or: [
{ author: "Rakesh" },
{ level: "high" }
]
}).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
}
]

Explanation: This query retrieves articles authored by “Aditya” with a level of “basic”, or authored by “Rakesh” with a level of “medium”.

4. Limit the Number of Results

The limit() method in MongoDB allows you to specify the maximum number of documents that should be returned in a query result. This is useful when you want to restrict the number of documents processed or displayed.

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
}
]

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

MongoDB Query Operators

MongoDB provides various operators that can be used to refine your queries:

  • $eq: Equal to
  • $gt: Greater than
  • $gte: Greater than or equal to
  • $lt: Less than
  • $lte: Less than or equal to
  • $ne: Not equal to
  • $in: Matches any value in an array
  • $nin: Matches none of the values in an array
  • $exists: Checks for the existence of a field
  • $or: Performs a logical OR operation

Conclusion

MongoDB queries are an essential tool for retrieving, filtering, and manipulating data in MongoDB collections. Whether we’re working with simple queries or complex conditions, MongoDB provides a rich set of operators and methods to make data retrieval efficient. By understanding the basics and advanced query techniques, you can easily perform powerful queries on MongoDB databases and effectively manage your data.

FAQs

What is a query in MongoDB?

A query in MongoDB is a request to retrieve data from a database based on specific criteria. It uses JSON-like syntax to filter, sort, and manipulate data in collections.

How to run the MongoDB query?

To run a query in MongoDB, use the find() method in the MongoDB shell or in a MongoDB client. The query parameters define the criteria for the data you want to retrieve.

What does a MongoDB query return?

A MongoDB query returns a cursor, which is an object that points to the result set. The data is retrieved iteratively, and you can use methods like toArray() to view the results as an array.



Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg