How to Add New Field to Every Document in a MongoDB Collection

Tahseen Tauseef Feb 02, 2024
  1. the $set Operator in MongoDB
  2. the $setOnInsert Operator in MongoDB
  3. Add New Field to Documents in a MongoDB Collection
How to Add New Field to Every Document in a MongoDB Collection

This article will discuss about the $set and $setOnInsert operation. Moreover, the problem of adding a field in collections in MongoDB is also briefly explained using these two operators.

the $set Operator in MongoDB

The $set operator changes a field’s value to the provided value. The $set operator expression looks like this: { $set: { <field1>: <value1>, ... } }.

Use dot notation to define a <field> in an embedded text or an array.

Behavior of the $set Operator

Update operators handle document fields with string-based names in lexicographic order starting in MongoDB 5.0. Numeric-named fields are handled in numerical order.

If the field does not already exist, $set will create one with the requested value, as long as the new field does not break a type restriction. If you give a dotted path for a field that doesn’t exist, $set will construct the embedded documents as needed to complete the dotted path.

$set will update or create each field if you supply multiple field-value pairs.

When you use an update operator like $set with an empty operand expression ({}) in MongoDB 5.0, mongod no longer throws an error. There are no modifications due to an empty update, and no oplog record is produced (meaning that the operation is a no-op).

For example, let us create the clothes collection:

db.clothes.insertOne(
   {
     _id: 100,
     quantity: 250,
     instock: true,
     reorder: false,
     details: { model: "14RR", make: "Clothes" },
     tags: [ "apparel", "clothing" ],
     ratings: [ { by: "Customer127", rating: 5 } ]
   }
)

Set Top-Level Fields

The following procedure utilizes the $set operator to alter the value of the quantity, details, and tags fields for the document meeting the criterion _id equal to 100.

db.clothes.updateOne(
   { _id: 100 },
   { $set:
      {
        quantity: 400,
        details: { model: "2600", make: "Fashionables" },
        tags: [ "coats", "outerwear", "clothing" ]
      }
   }
)

The operation updates the following:

  1. value of quantity to 400.
  2. details field with the new embedded document.
  3. tags field with the new array.

The document now has the following values:

{
  _id: 100,
  quantity: 400,
  instock: true,
  reorder: false,
  details: { model: '2600', make: 'Fashionables' },
  tags: [ 'coats', 'outerwear', 'clothing' ],
  ratings: [ { by: 'Customer127', rating: 5 } ]
}

Set Fields in Embedded Documents

Use dot notation to denote a <field> in an embedded text or an array. The following action modifies the make field in the details document for the document meeting the criterion _id equal to 100:

db.clothes.updateOne(
   { _id: 100 },
   { $set: { "details.make": "Kidz" } }
)

Following the update, the document now has the following values:

Set Fields in Embedded Documents - Output

Set Elements in Arrays

Use dot notation to denote a <field> in an embedded text or an array.

The following action modifies the value second element in the tags field and the ratings field in the first element of the ratings array for the document meeting the criterion _id equal to 100.

db.clothes.updateOne(
   { _id: 100 },
   { $set:
      {
        "tags.1": "rain wear",
        "ratings.0.rating": 3
      }
   }
)

Following the update, the document now has the following values:

Set Elements in Arrays - Output

the $setOnInsert Operator in MongoDB

If a document is inserted due to an update operation with upsert: true, then $setOnInsert applies the supplied values to the fields in the document. $setOnInsert does nothing if the update action does not result in an insert.

The upsert option can be specified.

Behavior of the $setOnInsert Operator

Update operators handle document fields with string-based names in lexicographic order starting in MongoDB 5.0. Numeric-named fields are handled in numerical order.

When you use an update operator like $setOnInsert with an empty operand expression ({}) in MongoDB 5.0, mongod no longer throws an error. There are no modifications due to an empty update, and no oplog record is produced (meaning that the operation is a no-op).

For example, the clothes collection contains no documents. We will insert a new document using db.collection.updateOne() with the upsert: true parameter.

db.clothes.updateOne(
  { _id: 1 },
  {
     $set: { item: "banana" },
     $setOnInsert: { defaultQty: 100 }
  },
  { upsert: true }
)

<query> is used by MongoDB to create a new document with the _id: 1 identifier. $setOnInsert makes the requested changes to the document.

The newly-inserted document is found in the clothes collection:

{ "_id" : 1, "item" : "banana", "defaultQty" : 100 }

When the upsert parameter is true, the db.collection.updateOne() method:

  1. Creates a new document,
  2. Applies the $set operation,
  3. Applies the $setOnInsert operation.

If db.collection.updateOne() matches an existing document, MongoDB only applies the $set operation.

Add New Field to Documents in a MongoDB Collection

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

Examples are also shown to use each method with a collection teams with the following documents:

db.teams.insertOne({team: "United", position: "Defence", points: 31})
db.teams.insertOne({team: "Spurs", position: "Defence", points: 22})
db.teams.insertOne({team: "Palace", position: "Center", points: 19})
db.teams.insertOne({team: "Eagles", position: "Forward", points: 26})
db.teams.insertOne({team: "Lions", position: "Defence", points: 33})

Add New Field Without Values

Syntax:

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

You 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}})

You can write the following query to view the first few updated documents:

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

This query returns the following documents:

Add New Field Without Values - Output

Add New Field With Specific Value

Syntax:

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

You 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}})

You can write the following query to view the first few updated documents:

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

This query returns the following documents:

Add New Field With Specific Value - Output

Add New Field Using Values From Existing Fields

Syntax:

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

You 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"]}}}
    ]
)

You can write the following query to view the first few updated documents:

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

This query returns the following documents:

Add New Field Using Values From Existing Fields - Output

Related Article - MongoDB Collection