How to use $set and $unset operators in MongoDB
MongoDB is a NoSQL database that stores data records in documents and not as rows and columns in tabular form. These documents are then grouped into collections.
Documents can be created, read, updated, and deleted. This is known as CRUD. To update existing document(s) within a collection, the following operations are available:
db.collection.updateOne()db.collection.findAndModify()db.collection.replaceOne()
All of the operations above can manipulate fields using operators. Two such operators for manipulating fields themselves within documents are:
$set$unset
Note: For this Answer, we'll use the
typescollection in thenumbersdatabase with four documents, as shown below.
The $setoperator
The $set operator sets the value of a specified field(s) in a document that matches the search criteria.
If the specified field(s) does not exist in the document, it is added with the specified value. However, if the specified field(s) does exist in the document, then the current value is updated with the value specified.
Syntax
The following code snippet provides the syntax for the $set operator.
{$set: {<field1>: <value1>,...}}
Example
For example, we add a field called count to the document with _id
Below is the code for the aforementioned example.
// Syntaxdb.types.updateOne({_id: 0},{$set: {count: 5}});// Printingdb.types.find({"_id":0})// Output// [{ _id: 0, name: 'evens', vals: [ 0, 2, 4, 6, 8 ], count: 5 }]
We can use this operator to update field values. The code below is used to change the value of the name field from evens to abcd for the document with _id
// Syntaxdb.types.updateOne({_id: 0},{$set: {name: "abcd"}});// Printingdb.types.find({"_id":0})// Output// [{ _id: 0, name: 'abcd', vals: [ 0, 2, 4, 6, 8 ] }]
The $unsetoperator
The $unset operator performs the inverse operation of the aforementioned $set operator. That is, it removes the specified field(s) from the document that matches the search criteria.
If the specified field(s) does not exist in the document, then the function call has no effect. However, if it does exist, the specified field(s) is deleted from the document.
Note: The value of this operator is always ignored.
Syntax
The following code snippet provides the syntax for the $unset operator.
{$unset: {<field1>: "",...}}
Example
For example, we can remove the name and vals field from the document with _id
Below is the code for the aforementioned example.
// Querydb.types.updateOne({_id: 1},{$unset: {name:"", vals:""}});// Printingdb.types.find({"_id":1})// Output// [{ _id: 1 }]
The code below can be used to see that specifying a field that doesn't exist will have no effect on the document.
// Querydb.types.updateOne({_id: 1},{$unset: {count:""}});// Printingdb.types.find({"_id":1})// Output// [{ _id: 1, name: 'odds', vals: [ 1, 3, 5, 7, 9 ] }]
Demo
The previously mentioned code snippets can be executed in the terminal below.
Free Resources