Open In App

How to Add a Column in MongoDB Collection?

Last Updated : 09 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Add New Field Without Values
  2. Add a New Field With a Specific Value
  3. 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:

productCollection2

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:

ADDFIELDWITHOUTVALUE

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:

ADDFIELDWITHVALUE

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:

USINGEXISTINGVALUE

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

In MongoDB, the flexibility to add fields to collections on-the-fly empowers developers to adapt swiftly to evolving requirements and enhance data structures without disrupting existing functionality. By leveraging methods like adding fields without values, initializing fields with specific values, or deriving new fields from existing data, MongoDB users can efficiently manage schema evolution and optimize data organization.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads