Page Content

Tutorials

What are the Field Update Operators in MongoDB?

Field Update Operators in MongoDB

Field Update Operators in MongoDB let you change individual fields inside a document without having to replace the entire thing. This is essential for atomic and effective operations and differs greatly from conventional RDBMS updates. While working on fields, these operators make sure the rest of your document stays unaltered.

Field Update Operators in MongoDB
Field Update Operators in MongoDB

The needed Field Update Operators are explained as follows:

Let’s use a collection named products with the following sample data:

db.products.insertMany([
    { "_id": 1, "name": "Laptop", "price": 1200, "stock": 50, "lastUpdated": ISODate("2024-01-15T10:00:00Z"), "status": "active" },
    { "_id": 2, "name": "Mouse", "price": 25, "stock": 100, "lastUpdated": ISODate("2024-02-01T14:30:00Z"), "status": "active" },
    { "_id": 3, "name": "Keyboard", "price": 75, "stock": 30, "lastUpdated": ISODate("2024-03-10T09:15:00Z"), "status": "active" },
    { "_id": 4, "name": "Monitor", "price": 300, "stock": 20, "lastUpdated": ISODate("2024-04-05T11:00:00Z"), "status": "active" }
]);

$inc Operator

To increase or decrease a field’s numerical value, use the $inc operator. It has the ability to add and subtract from numbers at will. $inc will create the field if it doesn’t already exist in the document. For situations like updating analytics, karma scores, or vote counts, this operator is quite helpful.

Key Points

Atomic Operation : $inc updates a key atomically. When many programs edit the same field at the same time, race situations are avoided since the process is completed as a single, uninterruptible unit.

Numerical Requirement: $inc must receive a number as input. An error will occur if you try to increase by a non-numeric value (such as a string or array).

Positional Operator: It can be used to increase a value inside an embedded array when combined with the positional operator ($).

Syntax:

{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }

Code Examples:

Increase the stock of “Mouse” by 50 units:

db.products.updateOne(
    { "name": "Mouse" },
    { $inc: { "stock": 50 } }
);

Decrease the stock of “Laptop” by 5 units (by providing a negative value):

db.products.updateOne(
    { "name": "Laptop" },
    { $inc: { "stock": -5 } }
);

$mul Operator

The $mul operator was first used for multiplicative increments in insert and update operations in MongoDB version 2.0.0. It lets you multiply a field’s value by a predetermined amount, just like $inc. Because $mul’s operations are atomic within a single document, frequently-changed fields in concurrent applications can be safely modified. Although the sources attest to its existence and functionality, there isn’t a clear code example that uses db.collection.update() with $mul.

Syntax:

{ $mul: { <field1>: <number1>, <field2>: <number2>, ... } }

Code Example:

Apply a 10% discount to the price of the “Monitor”:

db.products.updateOne(
    { "name": "Monitor" },
    { $mul: { "price": 0.9 } }
);

Double the stock of “Keyboard”:

db.products.updateOne(
    { "name": "Keyboard" },
    { $mul: { "stock": 2 } }
);

$rename Operator ($rename)

An existing key (field) in a document can have its name changed using the $rename operator. Both top-level fields and fields inside subdocuments can be renamed using this operator. It’s crucial to remember that field renaming adjustments may cause the fields in the document to be rearranged.

Syntax:

{ $rename: { <oldField1>: <newField1>, <oldField2>: <newField2>, ... } }

Code Example:

Rename the stock field to quantity for the “Laptop”:

db.products.updateOne(
    { "name": "Laptop" },
    { $rename: { "stock": "quantity" } }
);

Rename status to productStatus for all products:

db.products.updateMany(
    {}, // Affect all documents
    { $rename: { "status": "productStatus" } }
);

$currentDate Operator ($currentDate)

A field’s value is set to the current date using the $currentDate operator, which can be either a BSON Date or a BSON Timestamp. It’s helpful for keeping track of when an event happened or when a document was last edited.

Syntax:

{ $currentDate: { <field1>: <type|boolean>, <field2>: <type|boolean>, ... } }

Code Example:

Update the lastUpdated field of “Mouse” to the current date (BSON Date type):

db.products.updateOne(
    { "name": "Mouse" },
    { $currentDate: { "lastUpdated": true } }
);

Add a createdAt field (if not exists) or update it to the current Unix timestamp for “Keyboard”:

db.products.updateOne(
    { "name": "Keyboard" },
    { $currentDate: { "createdAt": { $type: "timestamp" } } }
);

$setOnInsert Operator

Operator $setOnInsert Specifically, upsert operations use the $setOnInsert operator. It makes sure that the value of a field is only set in the event that an insert is produced by the update operation (that is, if a new document is generated and no matching document is located). The field is not changed and the $setOnInsert operation is disregarded if a document is matched and updated. This is useful for setting up fields (such as default states or creation timestamps) without erasing them in later updates. In MongoDB 2.4, this operator was introduced.

Syntax:

{ $setOnInsert: { <field1>: <value1>, <field2>: <value2>, ... } }

Code Example:

Upsert a “Webcam” product. If it’s inserted, set createdAt and initialStock:

db.products.updateOne(
    { "name": "Webcam" }, // Filter for Webcam
    {
        $set: { "price": 40, "quantity": 100 }, // These fields will always be set/updated
        $setOnInsert: {
            "createdAt": new Date(), // Set only on insert
            "initialStock": 100,     // Set only on insert
            "source": "new_addition" // Set only on insert
        }
    },
    { upsert: true } // Crucial: enable upsert
);

Run the same upsert again for “Webcam” (it now exists):

db.products.updateOne(
    { "name": "Webcam" },
    {
        $set: { "price": 45, "quantity": 90 }, // These fields will be updated
        $setOnInsert: {
            "createdAt": new Date(), // Will NOT be set/updated as document exists
            "initialStock": 100
        }
    },
    { upsert: true }
);

$max Operator

The $max operator was added as an update operator for conditional updates in MongoDB 2.6. When $max is used as an update operator, it only modifies a field’s value if the value it specifies is higher than the field’s current value. This guarantees that the value of the field will never drop. Although its function as an update operator is explicitly stated in the sources, the published materials do not include a direct code sample that uses it in a db.collection.update() statement. Its application in aggregation, where it determines the maximum value inside a group, is different from this.

Syntax:

{ $max: { <field1>: <value1>, <field2>: <value2>, ... } }

Code Examples:

Increase the price of the “Mouse” if the new price is higher than the current one:

db.products.updateOne(
    { "name": "Mouse" },
    { $max: { "price": 30 } } // Current price is 25, so it will update to 30
);

Attempt to increase the price of “Keyboard” to 70 (which is lower than current 75):

db.products.updateOne(
    { "name": "Keyboard" },
    { $max: { "price": 70 } } // Current price is 75, so it will NOT update
);

$min Operator

In addition to $max, MongoDB 2.6 also introduces the $min operator for conditional updates. As an update operator, $min only modifies a field’s value if the value it contains is less than its current value. This guarantees that the value of the field will never rise. Like $max, although its use as an update operator is verified, the sources given do not include a direct code sample of its use in a db.collection.update() statement. Its application in aggregation, where it determines the lowest value inside a group, is distinct from this.

Syntax:

{ $min: { <field1>: <value1>, <field2>: <value2>, ... } }

Code Example:

Decrease the price of the “Laptop” if the new price is lower than the current one:

db.products.updateOne(
    { "name": "Laptop" },
    { $min: { "price": 1150 } } // Current price is 1200, so it will update to 1150
);

Attempt to decrease the price of “Monitor” to 350 (which is higher than current 300):

db.products.updateOne(
    { "name": "Monitor" },
    { $min: { "price": 350 } } // Current price is 300, so it will NOT update
);


$bit Bitwise Update Operator

You can carry out bitwise AND, OR, or XOR operations on integer numbers inside a document using the $bit operator. When handling flags or permissions that are represented as bits inside a numerical field, this can be helpful.

Syntax:

{ $bit: { <field>: { <bitwise-operator>: <numeric-value> } } }

Code Example:

db.products.updateOne(
    { "name": "Monitor" },
    { $set: { "flags": 0 } } // Initialize flags to 0 for Monitor
);

By frequently permitting in-place changes and atomic operations on individual documents, these field update operators provide strong and adaptable methods to alter data in MongoDB, enhancing its speed and resilience.

Index