MongoDB- ADD, MODIFY/RENAME, or DELETE Key
In MongoDB database, db.collection.update({criteria},{$operator: {new value}})
or db.collection.updateMany({criteria},{$operator: {new value}})
method is used to ADD, DELETE, or MODIFY/RENAME the existing document in the collection.
1. ADD
The $set
operator is used to adding a new key/field in the existing document.
Syntax:
{ $set: { <field1>: <value1>, ... } }
1.1. Add a new key in a single document
> db.employee.update({_id: ObjectId("5fa6b5d16230249b7475c770")},{ $set : { country : null} })
1.2. Add a new key in all document
> db.employee.updateMany({},{ $set : { country : null} })
2. MODIFY/RENAME
The $rename
operator rename/modify the name of a field/key of the existing document.
Syntax:
{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }
2.1. Rename key in a single document
> db.employee.update({_id: ObjectId("5fa6b5d16230249b7475c770")},{$rename: { "name": "fullName"} })
2.2. Rename key in all document
> db.employee.updateMany({},{$rename: { "name": "fullName"} })
3. DELETE
The $unset
operator deletes the specified field from the existing document.
Syntax:
{ $unset: { <field1>: "", ... } }
3.1. Delete key from a single document
> db.employee.update({_id: ObjectId("5fa6b5d16230249b7475c770")},{ $unset : { city : 1} })
3.2. Delete key from all document
> db.employee.updateMany({},{ $unset : { city : 1} })
References
- MongoDB- INSERT, SELECT, UPDATE, and DELETE Query
- How to set Username, Password, and Roles to MongoDB Database
- Field Update Operators- MongoDB Manual