4.2 C
London
Friday, December 20, 2024
HomeSoftware TutorialsMongoDBMongoDB: How to Add a New Field in a Collection

MongoDB: How to Add a New Field in a Collection

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following methods to add a new field to every document in a collection in MongoDB:

Method 1: Add New Field Without Values

db.collection.updateMany({}, {$set:{"new_field": null}})

Method 2: Add New Field With Specific Value

db.collection.updateMany({}, {$set:{"new_field": 10}}) 

Method 3: Add New Field Using Values from Existing Fields

db.collection.updateMany(
    {},
    [
        {"$set": {"name": { "$concat": ["$field1", " ", "$field2"]}}}
    ]
)

The following examples show how to use each method with a collection teams with the following documents:

db.teams.insertOne({team: "Mavs", position: "Guard", points: 31})
db.teams.insertOne({team: "Spurs", position: "Guard", points: 22})
db.teams.insertOne({team: "Rockets", position: "Center", points: 19})
db.teams.insertOne({team: "Warriors", position: "Forward", points: 26})
db.teams.insertOne({team: "Cavs", position: "Guard", points: 33})

Example 1: Add New Field Without Values

We can use the following code to add a new field called “rebounds” with a null value to every existing document in the collection:

db.teams.updateMany({}, {$set:{"rebounds": null}})

We can use the following query to view the first few updated documents:

db.teams.find().limit(3)

This query returns the following documents:

{ _id: ObjectId("6189325896cd2ba58ce928e5"),
  team: 'Mavs',
  position: 'Guard',
  points: 31,
  rebounds: null }

{ _id: ObjectId("6189325896cd2ba58ce928e6"),
  team: 'Spurs',
  position: 'Guard',
  points: 22,
  rebounds: null }

{ _id: ObjectId("6189325896cd2ba58ce928e7"),
  team: 'Rockets',
  position: 'Center',
  points: 19,
  rebounds: null }

Notice that each document now has a field called “rebounds” with a null value.

Example 2: Add New Field With Specific Value

We can use the following code to add a new field called “rebounds” with a value of 10 to every existing document in the collection:

db.teams.updateMany({}, {$set:{"rebounds": 10}})

We can use the following query to view the first few updated documents:

db.teams.find().limit(3)

This query returns the following documents:

{ _id: ObjectId("6189325896cd2ba58ce928e5"),
  team: 'Mavs',
  position: 'Guard',
  points: 31,
  rebounds: 10 }

{ _id: ObjectId("6189325896cd2ba58ce928e6"),
  team: 'Spurs',
  position: 'Guard',
  points: 22,
  rebounds: 10 }

{ _id: ObjectId("6189325896cd2ba58ce928e7"),
  team: 'Rockets',
  position: 'Center',
  points: 19,
  rebounds: 10 }

Notice that each document now has a field called “rebounds” with a value of 10.

Example 3: Add New Field Using Values from Existing Fields

We can use the following code to add a field called “name” whose value is a concatenation of the existing fields “team” and “position”:

db.teams.updateMany(
    {},
    [
        {"$set": {"name": { "$concat": ["$team", " ", "$position"]}}}
    ]
)

We can use the following query to view the first few updated documents:

db.teams.find().limit(3)

This query returns the following documents:

{ _id: ObjectId("618934cb96cd2ba58ce928ea"),
  team: 'Mavs',
  position: 'Guard',
  points: 31,
  name: 'Mavs Guard' }

{ _id: ObjectId("618934cb96cd2ba58ce928eb"),
  team: 'Spurs',
  position: 'Guard',
  points: 22,
  name: 'Spurs Guard' }

{ _id: ObjectId("618934cb96cd2ba58ce928ec"),
  team: 'Rockets',
  position: 'Center',
  points: 19,
  name: 'Rockets Center' }

Notice that each document now has a field called “name” whose value is a concatentation of the “team” and “position” fields.

Note: You can find the complete documentation for the updateMany() function here.

Additional Resources

The following tutorials explain how to perform other common tasks in MongoDB:

MongoDB: How to Rename Fields
MongoDB: How to Remove Fields
MongoDB: How to Check if Field Contains a String
MongoDB: How to Query with a Date Range
MongoDB: How to Query with “Like” Regex

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories