The basic usage of the mongodb UPDATE API is described in detail in the update operation of mongodb basic operations. The following section describes the common field update operators required by the update.

Update operators in mongodb are divided into three types: field update operator, array update operator and bitwise update operator. This paper introduces the commonly used field update operator in detail.

The following modifiers can be used for update operations;

For example, in the collection. The update () and the collection. The findAndModify ().

The syntax is as follows:

{

: {:,… },

: {:,… },

.

}

1. $set

Description:

The set operator sets the value of a field to the specified value if it does not exist, sets the value of a field to the specified value if it does not exist, and adds a new field with the specified value if it does not exist.

Grammar:

{ $set: { : , … }}

** Note: ** To specify a < field > in an embedded document or array, use dot notation.

1.1. The sample

Initialize data:

db.products.insert({

_id: 100,

sku: “abc123”,

quantity: 250,

instock: true,

reorder: false,

details: { model: “14Q2”, make: “xyz” },

tags: [ “apparel”, “clothing” ],

ratings: [ { by: “ijk”, rating: 4 } ]

})

1.1.1. Update individual object fields

Example: Query documents with a condition whose _ID is 100, using the $set operator to update the values of the Quantity, Details, and Tags fields.

db.products.update(

{ _id: 100 },

{ $set:

{

quantity: 500,

details: { model: “14Q3”, make: “xyz” },

tags: [ “coats”, “outerwear”, “clothing” ]

}

}

)

Query after change:

db.products.find({“_id”:100}).pretty()

Return result:

{

“_id” : 100,

“sku” : “abc123”,

“quantity” : 500,

“instock” : true,

“reorder” : false,

“details” : {

“model” : “14Q3”,

“make” : “xyz”

},

“tags” : [

“coats”,

“outerwear”,

“clothing”

].

“ratings” : [

{

“by” : “ijk”,

“rating” : 4

}

]

}

1.1.2. Update fields in embedded documents

Example: Query documents with a condition whose _ID is 100 and update the make field value in the Details object with the $set operator.

db.products.update(

{ _id: 100 },

{ $set: { “details.make”: “zzz” } }

)

Query after change:

db.products.find({“_id”:100}).pretty()

Return result:

{

“_id” : 100,

“sku” : “abc123”,

“quantity” : 500,

“instock” : true,

“reorder” : false,

“details” : {

“model” : “14Q3”,

“make” : “zzz”

},

“tags” : [

“coats”,

“outerwear”,

“clothing”

].

“ratings” : [

{

“by” : “ijk”,

“rating” : 4

}

]

}

1.1.3. Update array fields

Example: Query documents with a condition whose _ID is 100 and use the $set operator to update the values of the ratings field in the second element of the tags field (array index 1) and in the first element of the ratings array (array index 0).

db.products.update(

{ _id: 100 },

{ $set:

{

“tags.1”: “rain gear”,

“ratings.0.rating”: 2

}

}

)

Query after change:

db.products.find({“_id”:100}).pretty()

Return result:

{

“_id” : 100,

“sku” : “abc123”,

“quantity” : 500,

“instock” : true,

“reorder” : false,

“details” : {

“model” : “14Q3”,

“make” : “zzz”

},

“tags” : [

“coats”,

“rain gear”,

“clothing”

].

“ratings” : [

{

“by” : “ijk”,

“rating” : 2

}

]

}

2. $unset

Description:

The unset operator deletes a particular field if it does not exist, the unset operator deletes a particular field if it does not exist, and unset does nothing if it does not exist.

Grammar:

{ $unset: { : “”, … }}

2.1. The sample

Initialize data:

db.products.insert({

_id: 100,

sku: “abc123”,

quantity: 250,

instock: true,

reorder: false,

details: { model: “14Q2”, make: “xyz” },

tags: [ “apparel”, “clothing” ],

ratings: [ { by: “ijk”, rating: 4 } ]

})

Example: Filter out records whose SKU is ABC123 and delete the Quantity and Instock fields

db.products.update(

{ sku: “abc123” },

{ $unset: { quantity: “”, instock: “” } }

)

Query after change:

db.products.find({“sku”:”abc123″}).pretty()

Return result:

{

“_id” : 100,

“sku” : “abc123”,

“reorder” : false,

“details” : {

“model” : “14Q3”,

“make” : “zzz”

},

“tags” : [

“coats”,

“rain gear”,

“clothing”

].

“ratings” : [

{

“by” : “ijk”,

“rating” : 2

}

]

}

3. $setOnInsert

Description:

If the update operation causes the document to be inserted when the upsert parameter of the Update and findAndModify APIS is true, setOnInsert assigns the specified value to the fields in the document. If the update operation does not result in an insert, setOnInsert assigns the specified value to the field in the document. If the update operation does not result in an insert, setOnInsert assigns the specified value to the field in the document. If the update operation does not result in an insert, setOnInsert does nothing.

Grammar:

db.collection.update(

.

{ $setOnInsert: { : , … }},

{ upsert: true }

)

3.1. The sample

Initialize data:

db.products.insert({

_id: 100,

sku: “abc123”,

quantity: 250,

instock: true,

reorder: false,

details: { model: “14Q2”, make: “xyz” },

tags: [ “apparel”, “clothing” ],

ratings: [ { by: “ijk”, rating: 4 } ]

})

Example: Filter out records whose SKU is ABC123 and delete the Quantity and Instock fields

db.products.update(

{ _id: 100 },

{

$set: { item: “apple” },

$setOnInsert: { defaultQty: 100 }

},

{ upsert: true }

)

Query after change:

db.products.find({“_id”:100}).pretty()

Result: The defaultQty field is not inserted because a document record with ID 100 already exists. If it doesn’t exist

{document record with id 100, the defaultQty field is inserted

“_id” : 100,

“sku” : “abc123”,

“reorder” : false,

“details” : {

“model” : “14Q3”,

“make” : “zzz”

},

“tags” : [

“coats”,

“rain gear”,

“clothing”

].

“ratings” : [

{

“by” : “ijk”,

“rating” : 2

}

].

item” : “apple”

}

4. $rename

Description:

Update the name of the field. The new field name must be different from the existing field name.

Grammar:

{$rename: { : , : , … }}

Note:

The rename operator logically performs both the old name and the new name. The rename operator logically unsets both the old name and the new name, and then performs $set with the new name. Therefore, operations may not preserve the order of the fields in the document; That is, renamed fields can be moved around the document.

If there is already a field in the document, the $rename operator deletes the field and renames the specified field to.

If the field you want to rename does not exist in the document, $rename does nothing.

For fields in an embedded document, the rename operator can rename those fields and move them in or out of the embedded document. If these fields are in an array element, the rename operator can rename them and move them in or out of the embedded document. If these fields are in an array element, the rename operator can rename them and move them in or out of the embedded document. Rename has no effect if these fields are in an array element.

4.1. The sample

Initialize data:

db.students.insertMany([{

“_id”: 1,

“alias”: [ “The American Cincinnatus”, “The American Fabius” ],

“mobile”: “555-555-5555”,

“nmae”: { “first” : “george”, “last” : “washington” }

},

{

“_id”: 2,

“alias”: [ “My dearest friend” ],

“mobile”: “222-222-2222”,

“nmae”: { “first” : “abigail”, “last” : “adams” }

},

{

“_id”: 3,

“alias”: [ “Amazing grace” ],

“mobile”: “111-111-1111”,

“nmae”: { “first” : “grace”, “last” : “hopper” }

}])

4.1.1. Rename a single object field

Example: Rename the nMAE field to name

db.students.updateMany( {}, { $rename: { “nmae”: “name” } } )

Query after change:

db.students.find()

Return result:

{ “_id” : 2, “alias” : [ “My dearest friend” ], “mobile” : “222-222-2222”, “name” : { “first” : “abigail”, “last” : “adams” } }

{ “_id” : 3, “alias” : [ “Amazing grace” ], “mobile” : “111-111-1111”, “name” : { “first” : “grace”, “last” : “hopper” } }

{ “_id” : 1, “alias” : [ “The American Cincinnatus”, “The American Fabius” ], “mobile” : “555-555-5555”, “name” : { “first” : “george”, “last” : “washington” } }

4.1.2. Rename fields in embedded documents

To rename a field in an embedded document, invoke the $rename operator using dot notation to reference the field. If the field remains in the same embedded document, you can also use the dot symbol in the new name, as follows:

db.students.update( { _id: 1 }, { $rename: { “name.first”: “name.fname” } } )

Query after change:

db.students.find({“_id”:1})

Return result:

{ “_id” : 1, “alias” : [ “The American Cincinnatus”, “The American Fabius” ], “mobile” : “555-555-5555”, “name” : { “last” : “washington”, “fname” : “george” } }

5. $inc

Description:

Increments a field to a specified value. The operation accepts both positive and negative values. If the field does not exist, please inc to create this field and the field to the specified value, the null values on the fields of use inc to create the field and the field to the specified value, the null values on the fields of use inc to create the field and the field to the specified value, Using the INC operator on fields with null values produces an error.

Grammar:

{ $inc: { : , : , … }}

5.1. The sample

Initialize data:

db.products.insert({

_id: 1,

sku: “abc123”,

quantity: 10,

metrics: {

orders: 2,

Ratings: 3.5

}

})

Example: Decrease the quantity field value by 2, and increase the metrics. Orders field value by 1

db.products.update(

{ sku: “abc123” },

{ $inc: { quantity: -2, “metrics.orders”: 1 } }

)

Query after change:

db.products.find({“sku”:”abc123″}).pretty()

Return result:

{

“_id” : 1,

“sku” : “abc123”,

“quantity” : 8,

“metrics” : {

“orders” : 3,

“ratings” : 3.5

}

}

6. $currentDate

Description:

The currentDate operator sets the value of the field to the currentDate, which can be a date or timestamp. The default type is Date. If the field does not exist, the currentDate operator sets the value of the field to the currentDate, which can be a Date or timestamp. The default type is Date. If the field does not exist, the currentDate operator sets the value of the field to the currentDate, which can be a Date or timestamp. The default type is Date, and currentDate adds the field to the document if it does not exist.

Grammar:

{ $currentDate: { : , … }}

Can be:

A Boolean value, true, that sets the current date’s field value to a date, or

The document {type: “timestamp”} or {type: “date”} explicitly specifies the type. The operator is case sensitive and accepts only lowercase “timestamp” or lowercase “date”.

6.1. The sample

Initialize data:

db.customers.insertOne(

{ _id: 1, status: “a”, lastModified: ISODate(“2013-10-02T01:11:18.965Z”) }

)

Example: Update the lastModified field to the current date, add the Cancellation. Date field, set the value to the current timestamp, add the Cancellation. Reason field, set the value to user Request, and set the status field to D

db.customers.updateOne(

{ _id: 1 },

{

$currentDate: {

lastModified: true,

“cancellation.date”: { $type: “timestamp” }

},

$set: {

“cancellation.reason”: “user request”,

status: “D”

}

}

)

Query after change:

db.customers.find().pretty()

Return result:

{

“_id” : 1,

“status” : “D”,

“LastModified” : ISODate (” the 2021-01-21 T09:22:56. 639 z “),

“cancellation” : {

“date” : Timestamp(1611220976, 1),

“reason” : “user request”

}

}

Next mongodb Update manipulates arrays