Update Operators
1. Fields
MongoDB allows you to update the individual fields within a document.
Modifier |
Description |
---|---|
$set |
Set the value of a field. The field is created if it does not exist, and so can be used for dynamic updates or adding new fields to documents. |
$unset |
The entire field can be removed from the document without having to remove invalid data, allowing greater security. |
$rename |
If restructuring document schema requires a change in field name, it can be renamed while still maintaining existing value. |
2. Arrays
The following modifiers are useful for manipulating array data.
Modifier |
Description |
---|---|
$addToSet |
Adds unique elements to an array if they are missing and doesn’t add duplicate values. |
$pop |
Trims an array, dropping either the first or last element. |
$pull |
Allows elements in an array that match a particular query to be removed selectively based on some conditions. |
$push |
Adds an element to the end of an array, versatile and supports adding more than one element at a time. |
3. Modifiers
MongoDB offers modifiers that bring additional functionality to the update operation.
Modifier |
Description |
---|---|
$inc |
Adds to the current value of a field, particularly effective for numeric fields. Supports implementing counters or tracking numerical changes. |
$currentDate |
Setting the value of a field to current date and time, used for timestamping operations or making sure that each operation is able to reflect its last update. |
$setOnInsert |
During an insert operation, only particular fields are specified. These will be added upon a successful insert but have no effect during any update thereafter. |
4. Bitwise
Sub-Operator |
Description |
---|---|
$and |
Perform a bitwise AND operation |
$or |
Perform a bitwise OR operation |
$xor |
Perform a bitwise XOR operation |
$not |
Perform a bitwise NOT operation |
MongoDB Update Operators
MongoDB, one of the more popular NoSQL databases, provides several methods and functions for processing data. Updating documents is an important feature of working with MongoDB. In this article, we will understand the Update Operators with MongoDB in detail.
It is expected that readers have a basic knowledge of MongoDB, such as document structure and collections. Readers should also be familiar with CRUD operations before reading about update operators. You can start with some basic articles like MongoDB: An Introduction and What is MongoDB, How Does It Work And Its Features to get a comprehensive understanding.
The following modifiers can be used in update operations, such as db.collection.updateMany() and db.collection.findAndModify().