How to Add a Column in MongoDB Collection?
Last Updated :
30 Jul, 2024
In MongoDB, the ability to add new fields to collections without restructuring the entire schema is a powerful feature. Whether we are adapting to changing requirements or enhancing existing data, MongoDB offers several methods through easily we can easily add new fields to our collections.
In this article, we'll learn about How to add a column in MongoDB collection by understanding various methods with the help of examples and so on.
How to Add a Column in the MongoDB Collection?
When working with MongoDB, we often need to add or update documents to reflect changes in our data. MongoDB provides several methods to update documents, including the updateOne()
and updateMany()
methods. By using the update method let's understand How to add a column in the MongoDB collection as follows:
- Add New Field Without Values
- Add a New Field With a Specific Value
- Add New Field Using Values from Existing Fields
Let's set up an Environment:
To understand How to add a column in MongoDB collection we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called products which contains information like name, category, quantity, and brand of the products in various documents.
// Insert the documents into the 'products' collection
db.products.insertMany([
{
"_id": 1,
"name": "Laptop",
"price": 1200,
"category": "Electronics",
"quantity": 100,
"brand": "ABC Company"
},
{
"_id": 2,
"name": "Headphones",
"price": 100,
"category": "Electronics",
"quantity": 100,
"brand": "ABC Company"
},
{
"_id": 3,
"name": "T-Shirt",
"price": 20,
"category": "Clothing",
"quantity": 100,
"brand": "ABC Company"
}
]);
Output:

1. Add New Field Without Values
This method involves adding a new field to documents without specifying a value. We'll add a new field named in_stock to all documents without assigning any specific value.
db.products.updateMany({}, { $set: { in_stock: "" } });
Output:

Explanation: In the above query, It updates all documents in the "products" collection, by adding a new column called the "in_stock" field to an empty string for each document.
2. Add New Field With Specific Value
This method entails adding a new field to documents with a predefined value. We'll initialize a new field named discount_percentage with a value of 10 for all documents.
db.products.updateMany({}, { $set: { discount_percentage: 10 } });
Output:

Explanation: In the above query, It updates all documents in the "products" collection, by adding a new column called the "discount_percentage" field to 10 for each document.
3. Add New Field Using Values from Existing Fields
This method involves populating a new field in documents using values derived from existing fields within the same document. Let's calculate the total value for each product based on its price and quantity and add it as a new field named total_value.
// Add new field 'total_value' using values from existing fields 'price' and 'quantity'
db.products.aggregate([
{
$addFields: {
total_value: { $multiply: ["$price", "$quantity"] }
}
},
{
$out: "products" // Replace the existing collection with the updated documents
}
]);
Output:

Explanation:
- We use the $addFields stage to add a new field named total_value.
- Within the $addFields stage, we use the $multiply operator to calculate the total value by multiplying the price and quantity fields.
- The $out stage replaces the existing collection with the updated documents.
Conclusion
Adding fields to MongoDB documents is a versatile operation that can be performed in various ways depending on your needs. By using methods such as updateMany()
and aggregation pipelines, you can effectively manage and update your document schema to accommodate new data requirements.
Similar Reads
How Many Documents are in a MongoDB Collection?
In MongoDB, data is organized into collections and documents. A collection is a grouping of documents similar to a table in a relational database but without a fixed schema it allowing for flexible data structures. Documents on the other hand are JSON-like structures composed of key-value pairs whic
6 min read
How to Add a New Field in a Collection
Adding a new field to a MongoDB collection is a common task as applications grow and change. This process needs to be done carefully to ensure that existing data is not lost or corrupted. MongoDB provides several ways to add a new field while keeping our data safe and our application running smoothl
3 min read
How to Create Database and Collection in MongoDB
MongoDB is a widely used NoSQL database renowned for its flexibility, scalability, and performance in managing large volumes of unstructured data. Whether youâre building a small application or handling big data, MongoDB offers an easy-to-use structure for managing your data. In this article, we wil
6 min read
How to Rename Collection in MongoDB?
Renaming collections in MongoDB is a straightforward operation that helps in maintaining and organizing databases efficiently. MongoDB provides the renameCollection command and the db.collection.renameCollection() method for changing collection names within the same database.In this article, We will
3 min read
What is a collection in MongoDB?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for the storage and retrieval of data. Thi
4 min read
How to use TTL collections in MongoDB?
TTL (Time-To-Live) collections in MongoDB is a special collection where it allows automatic deletion of documents after a specified duration. This technique is used in managing temporary data, such as user sessions cache logsHow TTL WorksTTL Index: You create a TTL index on a date field in your coll
5 min read
How to Insert a Document into a MongoDB Collection using Node.js?
MongoDB, a popular NoSQL database, offers flexibility and scalability for handling data. If you're developing a Node.js application and need to interact with MongoDB, one of the fundamental operations you'll perform is inserting a document into a collection. This article provides a step-by-step guid
5 min read
Capped Collections in MongoDB
Creating a capped collection in MongoDB involves using the createCollection() method to define a collection with a fixed size and a maximum number of documents. Capped collections automatically overwrite old documents when they reach their size limit, making them ideal for use cases like logging or
5 min read
How to Copy a Collection From One Database to Another in MongoDB?
Effective data management is crucial for MongoDB-dependent applications. As databases grow, the need to transfer collections between databases arises. This can be for creating development or testing environments, migrating data, or archiving historical information. MongoDB provides built-in capabili
6 min read
How to drop collection in MongoDb using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read