MongoDB is NoSQL(Not only SQL) database because the storage and retrieval of data in MongoDB are not in the form of tables like in SQL. It stores data in a BSON structure. It uses BSON or Binary JSON data format to organize and store data. This data format includes all JSON data types and adds types for dates, different size integers, ObjectIds, and binary data. In MongoDB, a database is a physical container for the collections. It contains one or more collections. A MongoDB server has multiple databases inside it. A database stores data in the collection. A collection is a group of one or more documents that exists within a single database. A single collection contains different types of documents, which means if one document contains 10 fields then another document within the same collection may contain 20 fields. In this article, we will discuss the basic concept of MongoDB servers like databases, collections and documents and will mainly focus on MongoDB's Basic Queries of Database and Collection with the help of examples. This article will give you a quick start with MongoDB and make you comfortable with MongoDB Queries.
SHOW Statement
It is used to show all the databases present in the MongoDB server. It will not show you the newly created database until you add a collection to it. If you want to check the currently selected database then you can use db command.
Syntax:
show databases;
Example:
When you run the show databases command then it will show you all the databases present in MongoDB except databases that don't have any collection. In this example, company, myDatabase, test, and university are the user-defined databases, and admin, config, and local are built-in databases. One collection is important to insert into the database to display in the show databases command.
DB Statement
It is used to show the currently selected database. If the database doesn't contain any collection then the show databases command will not show that database in the list. So, to check which database we are using you need to use this command.
Syntax:
db;
Example:
In this example, we have created one database named university by using the use command. After that, we run the show databases command to check the list of databases in the MongoDb but there is no university database present in the MongoDB. The reason is university database doesn't contain any collection. So, to check the currently selected database use the db command.
USE Statement
It is used to create the new database and switch to that if the database does not exist in the MongoDB server or if the database exists then use command switches to the existing database.
Note: After creating a new database if you will do show databases then it will not show you the newly created database until you add a collection to it. If you want to check the currently selected database then you can use db command.
Syntax:
use <database_name>;
<database_name> is the name of the database. The database name should satisfy the naming convention of the MongoDB server database name.
Example:
use university;
In this example, we have created one new database named university by using the use command. It will also switch to the university database. You can check the currently selected database by using db command and you will get university in this example.
DROP Statement
It is used to drop/remove the database from MongoDB. To remove the database first you have to switch to the database which you want to drop by using the use command and then calling the dropDatabase() method on the selected database.
Syntax:
use <database-name>;
db;
db.dropDatabase();
Example:
use university;
db;
db.dropDatabase();
In this example, we are using the use command to switch to the database which we want to remove from the MongoDb server. After using the use command, check the current database to make sure that the database is switched properly by using db command. After you switched to the database, use dropDatabase() method on the selected database.
SHOW Statement
It is used to show all the collections present in the selected database.
Syntax:
db;
show collections;
Example:
Here, we first select the database whose collections list you want to check by using db command and then run show collections command to check the list of the collection present in the selected database.
CREATE Statement
This statement is used to create a collection within the selected database. createCollection() method will take the name of the collection as an argument. The collection name should not be a null or empty string, otherwise, it will throw an error.
Syntax:
db.createCollection("<name_of_collection>");
<name_of_collection> is the name of the collection. The collection name should satisfy the naming convention of the MongoDB collection name.
Example:
db.createCollection("teacher_contact_details");
In this example, we are creating the teacher_contact_details collection. Firstly, run the use command to switch to the university database in which we want to insert the collection. Then check the selected database by using db command. After that, call createCollection() method on the selected database and pass the collection name as an argument. To check whether the collection is inserted or not in the database run the show collections command.
DROP Statement
It is used to drop/remove the collection from the selected database. It will also removes any indexes associated with the dropped collection. To remove any collection from the selected database, call drop() method on that collection. If the collection is present in the database and it will be deleted successfully then it will return true. If the collection is not present in the database then it will return false.
Syntax:
db.<collection_name>.drop();
Example:
db.teacher_contact_details.drop();
In this example, we are dropping the collection named teacher_contact_details. Firstly, we run the use command to switch to the university database and then check whether the database is switched or not by using db command. After that, we use show collections command to check the list of the collections and then call the drop() method on the teacher_contact_details collection. It returns true means collection, as well as all indexes associated with it, are successfully deleted.
Find The Documents
It is used to find all the documents that satisfy the specified criteria in the selected collection.
Syntax:
db.<collection_name>.find(<filter>, <projection>);
- <filter> is a selection criterion used to select the documents. If we want all the documents in the selected collection then either omit the filter parameter or pass an empty document ({}).
- <projection> is used to select specific fields from the collection to include them in the output document. To include the field use 1. ' _id' is always included in the output document so to exclude it use _id : 0.
Note: Projection is used to improve the performance by optimizing the query. It reduces the fields in the document.
Example:
In the following example, we are using the find() method with no parameters that return all documents from a collection and return all fields of the documents. The following operation returns all the documents in the 'employee_details' collection which is present in the company database.
db.employee_details.find(); or db.employee_details.find({});
Find First Document
It is used to find the first document that satisfies the specified criteria on the selected collection. It only returns the first document in the collection if we have more than one documents that match the specified criteria.
Syntax:
db.<collection_name>.findOne(<filter>, <projection>);
- <filter> is a selection criterion used to select the document. If we pass an empty document ({}) as a filter then this method will return the first document in the collection.
- <projection> is used to select specific fields from the collection to include them in the output document. To include the field use 1. ' _id' is always included in the output document so to exclude it use _id : 0.
Example:
In the following example, we are using the findOne() method with no parameters that return the first document from the collection and returns all fields of the document.
db.employee_details.findOne() or db.employee_details.findOne({});
Find And Replace Document
It is used to replace the first document that satisfies the given criteria with the given replacement document. It is not used to update the fields. By default, it will return the original document. For returning the replacement document, set option 'returnNewDocument : true' in option section.
Syntax:
db.<collection_name>.findOneAndReplace(
<filter>,
<replacement> ,
<option>
);
- <filter> is a selection criterion used to select the document. If we pass an empty document ({}) as a filter then this method will replace the first document in the collection.
- <replacement> is a replacement document that replaces the first document that is selected by matching the specified filter.
- <option> is optional.
Example:
In the following example, we are using the findOneAndReplace() method which is used to replace the document that matches the specified filter with the replacement document.
db.employee_details.findOneAndReplace(
{"salary" : 30000},
{ "salary" : 40000,
"name": {"firstName" : "Rohit", "lastName" : "Khurana"},
}
);
- {"salary" : 30000} is the filter argument that matches the document to replace.
- { "salary" : 40000, "name": {"firstName" : "Rohit", "lastName" : "Khurana"} } is the replacement document.
- The following operation matches the document where salary field equals to 30000 from the 'employee_details' collection and replaces this document with { "salary" : 40000, "name": {"firstName" : "Rohit", "lastName" : "Khurana"} }. It returns the original document.
The following is the document after replacement:
{
"_id": {
"$oid": "629f87d1863729e229a35887"
},
"salary": 40000,
"name": {
"firstName": "Rohit",
"lastName": "Khurana"
}
}
Find And Delete Document
It is used to delete the first document that matches the specified filter. It returns the deleted document if the match is found otherwise returns null.
Syntax:
db.<collection_name>.findOneAndDelete(
<filter> ,
<option>
)
Here, <filter> is a selection criterion used to select the document. If we pass an empty document ({}) as a filter then this method will delete the first document in the collection.
Example:
In the following example, we are using the findOneAndDelete() method which is used to delete the first document that matches the specified filter.
db.employee_details.findOneAndDelete({"name.firstName" : "Rohit"});
- {"name.firstName" : "Rohit"} is the filter argument that matches the document to delete.
- The following operation selects the document where 'name.firstName' field equals 'Rohit' from the 'employee_details' collection and then deletes this document. It returns the deleted document.
Find And Update Document
It is used to update the first document that matches the given filter. It returns the original document. By default, it will returns the original document. For returning the updated document, set option 'returnNewDocument : true' in option section.
Syntax:
db.Students.findOneAndUpdate(
<filter> ,
<update>,
<option>
)
- <filter> is a selection criterion used to select the document. If we pass an empty document ({}) as a filter then this method will update the first document in the collection.
- <update> is a update document or aggregation pipeline.
- <option> is optional
Example:
In the following example, we are using the findOneAndUpdate() method which is used to update the document that matches the specified filter.
- {"name.firstName" : "Romal"} is the filter argument that matches the document to update.
- The {$set: {"address.phone.number" : 9876543210, "salary" : 80000} } specifies the change to apply. It uses the $set operator to set the value of the 'address.phone.number' field (Embedded Document) to '9876543210' and 'salary' field to '80000'
- The following operation selects the document where 'name.firstName' field equals 'Romal' from the 'employee_details' collection and then updates this document. It returns the original document.
db.employee_details.findOneAndUpdate(
{"name.firstName" : "Romal" },
{$set: {"address.phone.number" : 9876543210 , "salary" : 80000}
}
)
The following is the updated document.
{
"_id": {
"$oid": "629118c67017e180fa9ff11e"
},
"name": {
"firstName": "Romal",
"lastName": "Singla"
},
"address": {
"phone": {
"type": "Home",
"number": 9876543210
}
},
"salary": 80000,
"doj": {
"$date": "2022-05-26T18:30:00Z"
},
"skills": [
"React",
"MongoDB",
"Javascript"
]
}
Delete One Document
It is used to delete the first document that matches the filter. It only deletes the first document in the collection if we have more than one documents that match the specified criteria.
Syntax :
db.<collection_name>.deleteOne(<filter>);
Here, <filter> is a document that specifies the criteria for the deletion. If the filter matches more than one document, then the deleteOne() method deletes only the first document.
Example:
In the following example, we use the deleteOne() method to delete the document where "name.firstName" is "Rohit". The {"name.firstName" : "Rohit"} is the filter argument that matches the documents to delete. In this example, it matches the document whose name.firstName (Embedded Document) is "Rohit".
db.employee_details.deleteOne({"name.firstName" : "Rohit"});
The above operation returns the following document. Here, deletedCount containing the number of deleted documents
{ "acknowledged" : true, "deletedCount" : 1 }
Delete Many Documents
It is used to delete all the documents from the collection that matches the filter. If we pass an empty document ({}) then deleteMany() method removes all the documents from the collection. Please be careful while using this method.
Syntax:
db.<collection_name>.deleteMany(<filter>)
Here <filter> is a document that specifies the condition to select the document for deletion. If you pass an empty document ({}) into the deleteMany() method, it will delete all the documents from the selected collection.
Example:
In the following example, we use the deleteMany() method to delete all the documents that contain salary: 30000. The {"salary" : 30000 } is the filter argument that matches the documents to delete. In this example, it matches all the documents whose 'salary' : 30000.
db.employee_details.deleteMany({"salary" : 30000});
The above operation returns the following document. Here, deletedCount contains the number of deleted documents.
{ "acknowledged" : true, "deletedCount" : 3 }
Insert one document
It is used to insert one document inside the collection. It calls insertOne() method on collection in which we want to insert the document. If the collection does not exist, then the insertOne() method creates the collection.
Here, insertOne() method takes a document as an argument that is in BSON data format.
Syntax:
db.<collection_name>.insertOne(<document>);
Example:
In this example, we are creating one document by using insertOne() method with 5 fields named name, address, salary, doj, skills. The name holds object type, address holds document (Embedded Documents), salary holds number, doj holds date type, skills holds array type. This document doesn't hold '_id' field So, MongoDB creates and adds the '_id' key and assigns it a unique ObjectId() value.
db.employee_details.insertOne(
{
"name": {"firstName" : "Rohit", "lastName" : "Singla"},
"address": {
phone: { type: "Home", number: "000-000-000-7" }
},
"salary": 30000.00,
"doj": new Date('27 May 2022'),
"skills" : ["React", "MongoDB", "Javascript" ]
}
);
The above operation returns the following document:
{
"acknowledged" : true,
"insertedId" : ObjectId("62911cfe7017e180fa9ff122");
}
Insert multiple documents
It is used to insert multiple documents inside the collection. It calls insertMany() method on collection in which we want to insert the documents. Here, insertMany() method takes an array of documents as an argument which is in BSON data format.
Syntax:
db.<collection_name>.insertMany(
[
<document1>, <document2>, ...
]
);
Example:
In this example, we are creating two documents by using insertMany() method with 5 fields named city, state, country, pincode.
This document doesn't hold '_id' field So, MongoDB creates and adds the '_id' key and assigns it a unique ObjectId() value.
db.employee_details_contact.insertMany(
[
{
"city": "Hisar", "state": "Haryana",
"country" : "India" , "pincode" : "656565"
},
{
"city": "Gurgaon", "state": "Haryana",
"country" : "India" , "pincode" : "345678"
},
]
);
The above operation returns the following document:
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("629211cf7017e180fa9ff123"),
ObjectId("629211cf7017e180fa9ff124")
]
}
Update Document
It is used to modify the document or documents in the collection which satisfy the filter. This can update the existing document, completely replace the existing document or also add a new document to the collection. By using multi:true option, it can update all the documents which satisfies condition like updateMany() method.
Syntax:
db.<collection_name>.update(
<filter>,
<update>
)
- The <filter> is a document that specifies the criteria for the update.
- The <update> is a document that specifies the change to apply.
Example:
In the following example, we use the update() method to update the field 'address.phone.number' of the document where "name.firstName" is "Rohit".
- The {"name.firstName" : "Rohit"} is the filter argument that matches the documents to update. In this example, it matches the document whose name.firstName (Embedded Document) is "Rohit".
- The {$set : {"address.phone.number" : "111-111-111-8"} } specifies the change to apply. It uses the $set operator to set the value of the 'address.phone.number' field (Embedded Document) to "111-111-111-8".
db.employee_details.update(
{"name.firstName" : "Rohit"},
{
$set : {"address.phone.number" : "111-111-111-8"}
}
)
The above operation returns the following output, matchedCount indicates the number of documents that matched the criteria, and modifiedCount indicates the number of documents updated.
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Update One Document
It is used to update a single document. It only updates the first document in the collection if we have more than one documents that match the specified criteria.
Syntax:
db.<collection_name>.updateOne(
<filter>
<update>
)
- <filter> is a document that specifies the criteria for the update. If the filter matches more than one document, then the updateOne() method updates only the first document. If you pass an empty document {} into the method, it will only update the first document of the collection.
- <update> is a document that specifies the updates to apply.
Example:
In the following example, we use the updateOne() method to update the field pincode of the document with _id: 1. The updateOne() method will always modify a single document.
- The { _id : 1 } is the filter argument that matches the documents to update. In this example, it matches the document whose _id is 1.
- The { $set : {"pincode" : "1111111"} } specifies the change to apply. It uses the $set operator to set the value of the pincode field to 1111111.
db.employee_details_contact.updateOne(
{"_id" : 1},
{
$set : {"pincode" : "1111111"}
}
)
The above operation returns the following output, matchedCount indicates the number of documents that matched the criteria, and modifiedCount indicates the number of documents updated.
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Update Many documents
It is used to update all the documents in the collection that matches the specified criteria. This is similar to the update method when we use 'multi : true' option.
Syntax:
db.<collection_name>.updateMany(
<filter>
<update>
)
- <filter> is a document that specifies the condition to select the document for update. If you pass an empty document ({}) into the updateMany() method, it will update all the documents.
- <update> is a document that specifies the updates to apply.
Example:
In the following example, we use the updateMany() method to update the field salary of the document with salary: 20000. This method is used to update all the documents which satisfy the specified criteria.
- The {"salary":20000 } is the filter argument that matches the documents to update. In this example, it matches all the documents whose 'salary' : 20000.
- The { $set: {"salary":85000 } } specifies the change to apply. It uses the $set operator to set the value of the salary field to 85000.
db.employee_details.updateMany(
{"salary":20000 },
{
$set: {"salary":85000 }
}
)
The above operation returns the following output, matchedCount indicates the number of documents that matched the criteria, and modifiedCount indicates the number of documents updated.
{ "acknowledged" : true, "matchedCount" : 5, "modifiedCount" : 5 }
Similar Reads
MongoDB Tutorial MongoDB is an open source, document-oriented, NoSql database whose data is stored in an organized format. It is scalable and easy to learn, commonly used in modern web and mobile apps, dealing with high volumes of data. MongoDB stores data in BSON format, which lets you store JSON like documents eff
9 min read
Introduction
How do Document Databases Work?Document databases are a powerful tool in the world of NoSQL databases, and they play an important role in modern applications, especially where flexibility, scalability, and performance are key requirements. But how exactly do document databases work? In this article, we will go deep into the struc
6 min read
How MongoDB works ?MongoDB is an open-source document-oriented database. It is used to store a larger amount of data and also allows you to work with that data. MongoDB is not based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data, that is
4 min read
MongoDB: An introductionMongoDB is the most popular NoSQL open source document-oriented database. The term 'NoSQL' means 'non-relational'. This means that MongoDB is not based on a table like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of stora
4 min read
MongoDB: Getting StartedTerminologies: A MongoDB Database can be called the container for all the collections. A collection is a bunch of MongoDB documents. It is similar to tables in RDBMS.A document is made of fields. It is similar to a tuple in RDBMS, but it has a dynamic schema here. Documents of the same collection ne
5 min read
MongoDB - Working and FeaturesMongoDB is a powerful, flexible, and scalable NoSQL database that provides high performance and real-time data processing. Unlike traditional relational databases (RDBMS), MongoDB uses a document-oriented model, allowing developers to store and manage large volumes of unstructured or semi-structured
8 min read
Difference between RDBMS and MongoDBRDBMS and MongoDB both are widely used database management systems, but they differ significantly in how they store, manage and retrieve data. RDBMS (Relational Database Management System) is a traditional approach to database management, while MongoDB is a NoSQL (Non-relational) database known for
5 min read
MongoDB vs MySQLBoth MongoDB and MySQL are popular database management systems (DBMS), but they are built for different purposes and have distinct features. MongoDB is a NoSQL database, designed for handling unstructured data with high scalability, while MySQL is a traditional relational database management system
5 min read
Installation
How to Install and Configure MongoDB in Ubuntu?MongoDB is a popular NoSQL database offering flexibility, scalability, and ease of use. Installing and configuring MongoDB in Ubuntu is a straightforward process, but it requires careful attention in detail to ensure a smooth setup. In this article, we'll learn how to install and configure MongoDB i
5 min read
How to Install MongoDB on MacOSMongoDB is a leading open-source NoSQL database, known for its flexibility, scalability and high performance. It is widely used by companies like Adobe, Uber, IBM and Google for big data applications and real-time analytics. Unlike traditional relational databases, MongoDB stores data in documents (
6 min read
How to Install MongoDB on Windows?Looking to install MongoDB on your Windows machine? This detailed guide will help you install MongoDB on Windows (Windows Server 2022, 2019, and Windows 11) quickly and efficiently. Whether you are a developer or a beginner, follow this guide for seamless MongoDB installation, including setting up e
6 min read
Basics of MongoDB
MongoDB - Database, Collection, and DocumentMongoDB is a popular NoSQL database that offers a flexible, scalable, and high-performance way to store data. In MongoDB, Databases, Collections, and Documents are the fundamental building blocks for data storage and management. Understanding these components is crucial for efficiently working with
9 min read
MongoDB CursorIn MongoDB, a cursor is a powerful object that enables us to iterate over the results of a query. When we execute a query using methods like find(), MongoDB returns a cursor object that allows you to efficiently retrieve and process documents from the database one by one. Cursors provide various met
9 min read
DataTypes in MongoDBMongoDB, a leading NoSQL database, uses BSON (Binary JSON) format to store documents, offering a wide range of data types that allow flexible and efficient data storage. Understanding the different data types in MongoDB is crucial for designing effective schemas, optimizing queries, and ensuring sea
8 min read
What is ObjectId in MongoDBIn MongoDB, each document within a collection is uniquely identified by a field called _id. By default, this field uses the ObjectId format, a 12-byte BSON data type that ensures uniqueness and embeds valuable metadata, such as the creation timestamp. Understanding how ObjectId works is crucial for
5 min read
What is a MongoDB Query?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 t
10 min read
MongoDB - Create Database using Mongo ShellMongoDB is a popular NoSQL database that uses collections and documents, which are highly flexible and scalable. Unlike relational databases (RDBMS), MongoDB does not use tables and rows but stores data in a more dynamic, JSON-like format. In this article, we'll explore how to create a MongoDB datab
4 min read
MongoDB | Delete Database using MongoShellMongoDB is a NoSQL database system that uses dynamic schemas, making it highly flexible for developers. A MongoDB database acts as a container for collections, where each collection contains documents. In this article, we will explain how to delete databases in MongoDB using the db.dropDatabase() co
4 min read
MongoDB CRUD OperationsCRUD operations Create, Read, Update and Delete are essential for interacting with databases. In MongoDB, CRUD operations allow users to perform various actions like inserting new documents, reading data, updating records and deleting documents from collections. Mastering these operations is fundame
4 min read
MongoDB Methods
MongoDB - Insert() MethodThe insert() method in MongoDB is a fundamental operation used to add new documents to a collection. It allows inserting one or multiple documents in a single execution with MongoDB automatically generating a unique _id field if not explicitly provided. In this article, We will learn about the Mongo
6 min read
MongoDB insertOne() Method - db.Collection.insertOne()MongoDB is a powerful NoSQL database known for its flexibility, scalability, and performance. When working with MongoDB, one of the most common tasks is inserting data into collections. The insertOne() method is an essential tool in this process.In this article, We will learn about the MongoDB inser
5 min read
MongoDB insertMany() Method - db.Collection.insertMany()MongoDB insertMany() method is a powerful tool for inserting multiple documents into a collection in one operation. This method is highly versatile, allowing for both ordered and unordered inserts, and provides options for customizing the write concern. In this article, We will learn about insertMan
8 min read
MongoDB - Bulk.insert() MethodIn MongoDB, the Bulk.insert() method is used to perform insert operations in bulk. Or in other words, the Bulk.insert() method is used to insert multiple documents in one go. To use Bulk.insert() method the collection in which data has to be inserted must already exist. We will discuss the following
2 min read
MongoDB - bulkWrite() MethodThe bulkWrite() method in MongoDB is a powerful tool that allows for the execution of multiple write operations with a single command. This method is particularly useful for efficiently performing batches of operations, reducing the number of round trips to the database server and thus improving per
8 min read
MongoDB - Update() MethodMongoDB update operations allow us to modify documents in a collection. These operations can update a single document or multiple documents based on specified criteria. MongoDB offers various update operators to perform specific actions like setting a value, incrementing a value or updating elements
7 min read
MongoDB - updateOne() MethodMongoDB's updateOne() method provides a powerful way to update a single document in a collection based on specified criteria. This method is particularly useful when Accuracy is needed in modifying specific documents without affecting others.In this article, We will learn about MongoDBâs updateOne()
6 min read
MongoDB updateMany() Method - db.Collection.updateMany()MongoDB updateMany method is a powerful feature used to update multiple documents in a collection that match a specified filter. This method allows developers to efficiently perform bulk update operations, reducing network overhead and improving performanceIn this comprehensive guide, we will explor
6 min read
MongoDB - Find() Methodfind() method in MongoDB is a tool for retrieving documents from a collection. It supports various query operators and enabling complex queries. It also allows selecting specific fields to optimize data transfer and benefits from automatic indexing for better performance.In this article, We will lea
4 min read
MongoDB - FindAndModify() MethodThe findAndModify() method in MongoDB is a powerful and versatile tool for atomic updates on documents. This method allows us to perform multiple operations such as modifying, removing, or inserting documents while ensuring atomicity, meaning that no other operations can interfere during the modific
6 min read
MongoDB - FindOne() MethodMongoDB is a widely used NoSQL database that allows for flexible and scalable data storage. One of its essential methods findOne() which is used to retrieve a single document from a collection that matches the specified query criteria. This method is particularly useful when we need to fetch one spe
4 min read
MongoDB - findOneAndDelete() MethodMongoDB is a widely used NoSQL database that provides flexibility and scalability for handling large volumes of data. One of the key methods in MongoDB for document deletion is the findOneAndDelete() method. This method allows us to delete a single document from a collection based on specified crite
6 min read
MongoDB - db.collection.findOneAndReplace() MethodThe findOneAndReplace() method in MongoDB is a powerful tool for finding and replacing a single document within a collection. This method replaces the first document that matches the specified criteria with a new one. By default, it returns the original document but this can be configured to return
6 min read
MongoDB - db.collection.findOneAndUpdate() MethodThe MongoDB findOneAndUpdate() method is used to update the first matched document in a collection based on the selection criteria. It offers various options such as sorting, upserting, and returning the updated document. This method is a part of MongoDB's CRUD operations and provides an easy-to-use
5 min read
MongoDB - sort() MethodThe sort() method in MongoDB is an essential tool for developers to order documents returned by queries in a specified manner. By utilizing the sort() method, we can organize our query results in either ascending (1) or descending (-1) order based on one or more fields. MongoDB supports complex sort
6 min read
MongoDB - copyTo() MethodMongoDB copyTo() method is used to duplicate the contents of one collection into another collection within the same database. It's like making a copy of a file on your computer to another location. In this article, We will learn about MongoDB copyTo() Method with the help of examples and so on.Mongo
3 min read
MongoDB Count() Method - db.Collection.count()MongoDB's count() method is a powerful tool for retrieving the number of documents in a collection that match a specified query. It offers flexibility in filtering and is useful for obtaining quick counts based on various criteria.In this article, We will explain the MongoDB count() method in detail
5 min read
MongoDB - countDocuments() MethodMongoDB provides powerful methods to manage and retrieve data efficiently. One such method is countDocuments(), which allows us to count the number of documents in a collection that match a specified query filter. This method is particularly useful when dealing with large datasets, ensuring accurate
5 min read
MongoDB - Drop CollectionIn MongoDB, managing collections is a fundamental aspect of database operations. The MongoDB drop collection command allows us to permanently delete an entire collection along with its documents and indexes. By using the db.collection.drop() method is essential when we need to clear outdated data or
4 min read
MongoDB Remove() Method - db.Collection.remove()The MongoDB remove() method allows users to remove documents from a collection based on specific criteria. It is a powerful tool in MongoDB that enables both single and bulk document deletion, offering flexibility in managing your database. It supports various options like removing only one document
5 min read
MongoDB - db.collection.deleteone()The MongoDB deleteOne() method is an essential tool for removing a single document from a collection that matches a specified filter. It is widely used for precise deletion tasks, ensuring that we can manage your MongoDB collections effectively by removing specific documents based on certain criteri
4 min read
MongoDB - Distinct() MethodThe distinct() method in MongoDB is a powerful tool used to find unique values for a specified field across a single collection. By retrieving all distinct values associated with a specific key, this method helps eliminate duplicates and enables better analysis and reporting on the dataset.In this a
3 min read
MongoDB - limit() MethodThe limit() method in MongoDB is a powerful tool used to control the number of documents returned in a query result. It is particularly beneficial when working with large collections as it allows for the restriction of result set sizes thereby improving performance and reducing client load. In this
5 min read
MongoDB - skip() MethodWhen working with large datasets in MongoDB, efficient data retrieval becomes crucial. The MongoDB skip() method is an essential tool that allows developers to control which portion of the dataset is returned, improving performance and enabling better data paginationWhat is MongoDB skip()?In MongoDB
4 min read
MongoDB | ObjectID() FunctionObjectID() Function: MongoDB uses ObjectID to create unique identifiers for all the documents in the database. It is different than the traditional autoincrementing integer ID, but it comes with its own set of advantages. An ObjectID is a GUID (Globally Unique Identifier). GUIDs are generated random
2 min read
MongoDB - db.collection.CreateIndex() MethodMongoDB's createIndex() method is used to create indexes on collections which allows for efficient querying and sorting of data. This method supports various types of indexes like text indexes, 2dsphere indexes, 2d indexes and more. It also provides options to customize the index creation process.In
7 min read
createIndexes() Method in MongoDBMongoDB is a highly scalable NoSQL database that allows flexible data storage. One of the most powerful features for improving query performance is indexing. The createIndexes() method in MongoDB allows developers to create various types of indexes which significantly improve query execution speed a
5 min read
MongoDB - getIndexes() MethodIn MongoDB, managing indexes is important for optimizing query performance. The getIndexes() method provides a straightforward way to retrieve information about the indexes on a specific collection. Understanding how to use this method effectively helps developers analyze and manage their indexing s
4 min read
MongoDB dropIndex() MethodIndexes are important in MongoDB for improving query performance, allowing the database to quickly find the documents that match query criteria. The dropIndex() method in MongoDB enables developers to manage their collection's indexes by removing unnecessary or outdated indexes. However, it's import
5 min read
MongoDB - dropIndexes() MethodThe MongoDB dropIndexes command is an important tool for managing and optimizing database performance. By removing unnecessary indexes, we can free up system resources and ensure faster query execution. In this article, weâll explore the dropIndexes() in MongoDB and explain how to use the MongoDB in
3 min read
Comparison Operators
MongoDB - Comparison Query OperatorsMongoDB provides powerful comparison query operators to filter and retrieve documents based on field values. These operators help developers perform precise queries, enabling efficient data retrieval and manipulation. MongoDB uses various comparison query operators to compare the values of the docum
4 min read
MongoDB $cmp OperatorThe MongoDB $cmp operator is a powerful tool for comparing two values within documents, commonly used in aggregation pipelines for sorting or conditional operations. It plays a crucial role in sorting, conditional operations, and advanced comparisons inside MongoDB queriesIn this article, We will le
4 min read
MongoDB $gt OperatorThe $gt operator in MongoDB is a powerful comparison operator that allows you to query documents where the value of a field is greater than a specified value. It can be used in various methods, such as find, update, and aggregate, making it a flexible tool for data analysis and retrieval.In this gui
4 min read
MongoDB - $lt OperatorMongoDB provides powerful query operators to filter and retrieve data efficiently. One such essential operator is the $lt (less than) operator, which allows users to select documents where a specified fieldâs value is less than a given value. We can use this operator in methods like, find(), update(
4 min read
MongoDB - $eq OperatorMongoDB provides a variety of comparison query operators to filter and retrieve documents efficiently. One of the most widely used operators is $eq (equal to operator), which allows users to match exact values in a MongoDB collection.In this article, we will explore the MongoDB $eq operator, its syn
4 min read
MongoDB - $lte OperatorMongoDB $lte Operator is one of the comparison operators. $lte operator selects those documents where the field value is less than equal to (<=) the given value. This operator can be used in methods like find(), update(), etc. according to your requirements.. Syntax{field: {$lte: value}}MongoDB $
2 min read
MongoDB - $gte OperatorMongoDB $gte or "greater than equals to" operator is one of the comparison operators. $gte operator selects those documents where the field value is greater than equals to(>=) the given value. This operator can be used in methods (like, find(), update(), etc.) according to your requirements. Synt
2 min read
MongoDB - $ne OperatorMongoDB $ne or "not equals" operator is one of the comparison operators. The $ne operator selects those documents where the field value is not equal to the given value. It also includes those documents that do not contain the specified field. You can use this operator in methods like find(), update(
2 min read
MongoDB $in OperatorMongoDB $in operator provides a powerful way to query documents based on multiple potential values for a specific field within a single query.In this article, We will learn about the MongoDB $in Operator by understanding various examples in detail.MongoDB $in OperatorThe MongoDB $in operator is used
4 min read
MongoDB - $nin OperatorMongoDB $nin or " not in" is one of the comparison query operators. The $nin operator selects those documents where the field value is not equal to any of the given values in the array and the field that does not exist. You can use this operator in methods like find(), update(), etc. according to yo
2 min read
Logical Operators
Arithmetic Operators
MongoDB $add OperatorThe $add operator in MongoDB is a versatile and essential tool within the aggregation framework. It enables us to perform arithmetic operations like addition on numeric values, as well as concatenate dates and numbers. Whether we are aggregating data or manipulating documents, the $add operator is i
4 min read
MongoDB $subtract OperatorMongoDBâs $subtract operator is an essential tool in the aggregation pipeline, allowing users to perform subtraction operations on numbers, dates, and even date-time calculations. This powerful operator simplifies arithmetic operations within the aggregation pipeline and enhances MongoDB's ability t
4 min read
MongoDB $multiply OperatorIn MongoDB, the $multiply operator is a powerful tool used in aggregation pipelines to perform multiplication operations. This operator takes one or more expressions as arguments and multiplies them to produce a result.In this article, we will explain the MongoDB $multiply operator, its syntax, usag
4 min read
MongoDB $divide OperatorIn MongoDB, the $divide operator is a powerful tool used to perform division between two numerical values. It allows for precise arithmetic operations directly within the database queries, enhancing the capability to manipulate and analyze data. In this article, We will learn about the MongoDB $divi
4 min read
MongoDB $abs operatorThe $abs operator in MongoDB is a fundamental arithmetic expression operator used in aggregation pipeline stages. Its primary function is to calculate the absolute value of a specified number. This operation ensures that only positive values are considered, regardless of the numberâs sign, making it
4 min read
MongoDB $floor OperatorThe MongoDB $floor operator is a powerful tool used in the aggregation pipeline to round numbers down to the nearest integer that is less than or equal to the original number. Whether we're working with employee performance metrics, financial data, or any numerical dataset, the $floor operator helps
4 min read
MongoDB $ceil OperatorIn MongoDB, the $ceil operator is a powerful tool used in aggregation pipelines to round numbers up to the nearest integer greater than or equal to the original number. In this article, We will learn about the MongoDB $ceil Operator in detail. MongoDB $ceil OperatorMongoDB $ceil operator is used in
3 min read
MongoDB $mod OperatorMongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages and $mod operator is one of them. This operator is used to divide one number by another number and return the remainder. Syntax: { $mod: [ <expression1>, <expression2> ] }
1 min read
MongoDB $sqrt OperatorMongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages $sqrt operator is one of them. This operator is used to find the square root of a positive number and returns the result as a double. Syntax: { $sqrt: <number> } Here, the numbe
2 min read
MongoDB $pow OperatorMongoDB's $pow operator is a powerful tool within the aggregation framework which is designed to compute exponentiation operations directly on numeric fields. In this article, We will learn about the MongoDB $pow Operator in detail by understanding various examples and so on.MongoDB $pow OperatorThe
4 min read
MongoDB $exp OperatorMongoDB's aggregation framework provides a powerful set of tools for data manipulation and processing. One such tool is the $exp operator which allows users to perform exponential calculations within aggregation pipelines. In this article, We will learn about the MongoDB $exp Operator in detail. Mon
3 min read
MongoDB $log OperatorThe MongoDB $log operator is used within the aggregation pipeline to calculate the logarithm of a number with a specified base. This operator helps perform logarithmic calculations on fields whether in simple documents or embedded documents. The syntax is straightforward by requiring a number and a
3 min read
MongoDB $log10 OperatorIn MongoDB, the $log10 operator is a powerful tool that allows users to perform mathematical computations directly within the database. This operator returns the base 10 logarithm of a specified number and making it invaluable for data analysis and transformation tasks. In this article, We will lear
3 min read
MongoDB $ln Operator$in operator in MongoDB is a powerful query tool used to filter documents based on whether a field value matches any value within a specified array. This operator simplifies searching through large datasets by allowing developers to specify multiple values for a single field. In this article, we wil
5 min read
Field Update Operators
MongoDB - Field Update OperatorsMongoDB offers a range of powerful field update operators that enable efficient modification of specific fields within documents. These operators allow developers to update specific fields in documents without rewriting the entire document, thus improving performance and operational efficiency.By gu
5 min read
MongoDB - $max OperatorThe $max operator in MongoDB is one of the field update operators used to conditionally update fields within a document. It updates a field only if the specified value is greater than the current value, making it highly efficient for managing thresholds and ensuring data accuracy. This operator is v
4 min read
MongoDB - $min OperatorMongoDB offers a range of powerful update operators, and one of the most useful is the $min operator. This operator updates a field's value to a specified value, but only if that value is smaller than the current field value. If the specified value is greater than or equal to the current value, no u
5 min read
MongoDB - $inc OperatorThe MongoDB $inc operator is one of the most commonly used update operators in MongoDB, especially when it comes to modifying numerical values within documents. It is used to increment or decrement the value of a field by a specific amount, making it highly useful for applications like counters, sco
5 min read
MongoDB - $mul OperatorMongoDB $mul operator is a powerful update operator used to multiply the value of a field by a specified number. This operator allows for direct arithmetic operations within the database, making it particularly useful for scenarios that require modifying numeric field values without needing to retri
5 min read
MongoDB - Rename Operator ($rename)MongoDB $rename operator is a powerful tool for for efficiently renaming fields within documents. This operator ensures data consistency and helps developers maintain a clear and organized schema, especially when working with large collections. Whether youâre dealing with nested documents, arrays, o
5 min read
MongoDB - Current Date Operator ($currentDate)MongoDB provides different types of field update operators to update the values of the fields of the documents and $currentDate operator is one of them. This operator is used to set the value of a field to the current date (either as a timestamp or as a Date). The default type of $currentDate operat
2 min read
MongoDB - $setOnInsert OperatorThe $setOnInsert operator in MongoDB is a powerful tool used in updating operations with the upsert option. It allows us to specify values that should be set only when a new document is inserted. In this article, we will learn about the $setOnInsert Operator in MongoDB in detail and so on. MongoDB $
4 min read
MongoDB Bitwise Update OperatorThe MongoDB Bitwise Update Operator allows for efficient manipulation of integer fields within MongoDB documents through bitwise operations. In this article, We will learn about the MongoDB Bitwise Update Operator in detail by understanding various examples in detail.MongoDB Bitwise Update OperatorM
3 min read
Array Expression Operators