Add a new field to each document in a MongoDB collection
This article will discuss the $set and $setOnInsert operations. In addition, the issue of adding fields to a collection in MongoDB is also briefly explained using these two operators.
$set operator in MongoDB
The $set operator changes the value of a field to a supplied value. The $set operator expression is as follows: { $set: { <field1>: <value1>, ... } }
.
Use dot notation to define inline text or arrays <field>
.
Behavior of the $set Operator
Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. Fields named with numbers are processed in numeric order.
If the field does not exist, $set will create one with the requested value, as long as the new field does not break type restrictions. If you provide a dotted path to a nonexistent field, $set will construct embedded documents as necessary to complete the dotted path.
If you provide multiple field-value pairs, $set will update or create each field.
mongod no longer throws an error when you use an update operator such as $set with an empty operand expression ( ) in MongoDB 5.0 {}
. Since the update is empty, no modification is made and no oplog record is generated (meaning the operation is a no-op).
For example, let's create a collection of clothes:
db.clothes.insertOne(
{
_id: 100,
quantity: 250,
instock: true,
reorder: false,
details: { model: "14RR", make: "Clothes" },
tags: [ "apparel", "clothing" ],
ratings: [ { by: "Customer127", rating: 5 } ]
}
)
Setting Top-Level Fields The following procedure uses the $set operator to change _id
the values of the Quantity, Details, and Tags fields for documents that satisfy the condition equal to 100.
db.clothes.updateOne(
{ _id: 100 },
{ $set:
{
quantity: 400,
details: { model: "2600", make: "Fashionables" },
tags: [ "coats", "outerwear", "clothing" ]
}
}
)
This operation updates the following:
- The quantity value is 400.
- Details field for the new embedded document.
- Label the fields with the new array.
The document now has the following values:
{
_id: 100,
quantity: 400,
instock: true,
reorder: false,
details: { model: '2600', make: 'Fashionables' },
tags: [ 'coats', 'outerwear', 'clothing' ],
ratings: [ { by: 'Customer127', rating: 5 } ]
}
Setting fields in embedded documents
Use dot notation to represent embedded text or arrays <field>
. The following operation modifies _id
the make field in the detail document of documents that satisfy the condition equal to 100:
db.clothes.updateOne(
{ _id: 100 },
{ $set: { "details.make": "Kidz" } }
)
After the update, the document now has the following values:
Set the elements in an array
Use dot notation to represent text or arrays embedded in the text <field>
.
The following operation modifies the value in the second element of the tags field and the ratings field in the first element of the ratings array to satisfy the condition _id
equal to 100 for the document.
db.clothes.updateOne(
{ _id: 100 },
{ $set:
{
"tags.1": "rain wear",
"ratings.0.rating": 3
}
}
)
After the update, the document now has the following values:
$setOnInsert operator in MongoDB
If the document was inserted as a result of an update operation, upsert: true
$ setOnInsert applies the provided value to the field in the document. If the update operation did not result in an insert, **$setOnInsert** does nothing.
The ups****ert option can be specified.
Behavior of the $setOnInsert operator
Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. Fields named with numbers are processed in numeric order.
mongod no longer throws an error when you use an update operator such as $setOnInsert with an empty operand expression ( ) in MongoDB 5.0 {}
. Since the update is empty, no modification is made and no oplog record is generated (meaning the operation is a no-op).
For example, the clothes collection contains no documents. We will insert a new document using insert with upsert: true
the parameter .db.collection.updateOne()
db.clothes.updateOne(
{ _id: 1 },
{
$set: { item: "banana" },
$setOnInsert: { defaultQty: 100 }
},
{ upsert: true }
)
<query>
Used by MongoDB to create a _id: 1
new document with the identifier $setOnInsert Makes the requested changes to the document.
Find the newly inserted document in the clothes collection:
{ "_id" : 1, "item" : "banana", "defaultQty" : 100 }
When the upsert parameter is true, db.collection.updateOne()
the method:
- Create a new document,
- Apply the $set operation,
- Apply the $setOnInsert action.
db.collection.updateOne()
MongoDB only applies the $set operation
if there is a match with an existing document.
Adding new fields to documents in a MongoDB collection
You can use the following method to add a new field to each document in a MongoDB collection.
Also shown are examples of using each method with a collection team with the following documents:
db.teams.insertOne({team: "United", position: "Defence", points: 31})
db.teams.insertOne({team: "Spurs", position: "Defence", points: 22})
db.teams.insertOne({team: "Palace", position: "Center", points: 19})
db.teams.insertOne({team: "Eagles", position: "Forward", points: 26})
db.teams.insertOne({team: "Lions", position: "Defence", points: 33})
Add a new field with no value
syntax:
db.collection.updateMany({}, {$set:{"new_field": null}})
You can use the following code to add a new field called rebounds with an empty value to every existing document in the collection:
db.teams.updateMany({}, {$set:{"rebounds": null}})
You can write the following query to view the first few updated documents:
db.teams.find().limit(3)
This query returns the following documents:
Add a new field with a specific value
syntax:
db.collection.updateMany({}, {$set:{"new_field": 10}})
You can use the following code to add a new field named rebounds with a value of 10 to every existing document in the collection:
db.teams.updateMany({}, {$set:{"rebounds": 10}})
You can write the following query to view the first few updated documents:
db.teams.find().limit(3)
This query returns the following documents:
Add a new field using the value from an existing field
syntax:
db.collection.updateMany(
{},
[
{"$set": {"name": { "$concat": ["$field1", " ", "$field2"]}}}
]
)
You can use the following code to add a field called name whose value is the concatenation of the existing fields team and position.
db.teams.updateMany(
{},
[
{"$set": {"name": { "$concat": ["$team", " ", "$position"]}}}
]
)
You can write the following query to view the first few updated documents:
db.teams.find().limit(3)
This query returns the following documents:
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Date comparison in MongoDB
Publish Date:2025/04/28 Views:169 Category:MongoDB
-
This MongoDB tutorial discusses the issue of returning Date-based queries. In addition, there is also a good tutorial on how to use Date Range queries in MongoDB. Using date ranges in MongoDB We will learn to write MongoDB date range querie
Find objects between two dates in MongoDB
Publish Date:2025/04/28 Views:94 Category:MongoDB
-
In this article, the problem of finding objects between two dates was briefly discussed. In addition, the operators $gte, $lte, $gt, and $lt used for this purpose were briefly explained in detail. Querying date ranges in MongoDB This sectio
Comparing Dates in MongoDB
Publish Date:2025/04/28 Views:115 Category:MongoDB
-
Date is a common field in most databases, and sometimes we need to find exact documents from a collection in MongoDB. For example, if we have a collection of orders, we might search for those documents before or after a specific date. In th
Convert string to date in MongoDB
Publish Date:2025/04/28 Views:162 Category:MongoDB
-
MongoDB is an excellent platform that is growing in popularity. Among the various features it offers, MongoDB also allows you to convert data from one type to another. This may seem like a complex function, but it is very simple to execute.
Building the MongoDB REST API
Publish Date:2025/04/28 Views:70 Category:MongoDB
-
MongoDB is a flexible and scalable document-oriented database system that is widely used for large-volume data storage. It uses documents and collections instead of the traditional rational database approach of using tables and rows. MongoD
Using ORM with MongoDB
Publish Date:2025/04/28 Views:117 Category:MongoDB
-
MongoDB introduces a NoSQL solution for data storage and management, consisting of documents represented in JSON style. Like other database systems, MongoDB can also use ORM. In this article, we will explain the concepts of ORM and general
Locking mechanism in MongoDB
Publish Date:2025/04/28 Views:95 Category:MongoDB
-
In database management systems, locking mechanisms ensure the consistency of the entire result. For example, if some writing process is in progress on the data, a read command cannot be executed at the same time. Database resources are lock
Unique Index in MongoDB
Publish Date:2025/04/28 Views:130 Category:MongoDB
-
In this article, you'll learn about unique indexes, including what they are and how to create them in MongoDB. Additionally, the process of making a user's email unique in MongoDB is briefly described. The contents of this article are as fo
Creating Indexes in MongoDB
Publish Date:2025/04/28 Views:178 Category:MongoDB
-
Indexes help resolve queries efficiently. Without indexes, MongoDB must iterate through every document in the collection to find the documents that match the query. It will waste time and require MongoDB to handle such information. Therefor