How to use updateOne() Method with $set Operator In Databases
- The updateOne() is the MongoDB method used to update a single document in a collection based on a filter condition.
- The method accepts three parameters: a query filter, an update operation, and an optional update options document.
Example 1: Adding the new field [Duration] with value 30 days
The below query updates the Duration field to 30 days for the document with the ObjectId “6616b9f157bac1647326e11d” in the courses collection
db.courses.updateOne(
{ _id: ObjectId("6616b9f157bac1647326e11d") }, // Specify the document by its ObjectId
{ $set: { Duration: "30 days" } }
)
Output:
Example 2: Adding the new field [Student_enrolled] with value 67
The below query updates the Student_enrolled field to 67 for the document with the ObjectId “6616b9f157bac1647326e11d” in the courses collection
db.courses.updateOne(
{ _id: ObjectId("6616b9f157bac1647326e11d") }, // Specify the document by its ObjectId
{ $set: { "Student_enrolled": 67 } }
)
Output:
How to Add a New Field in a Collection
Adding a new field to a MongoDB collection is a common task as applications grow and change. This process needs to be done carefully to ensure that existing data is not lost or corrupted. MongoDB provides several ways to add a new field while keeping our data safe and our application running smoothly.
In this article, We will learn about How to Add a New Field in a Collection by understanding various method along with methods practical examples and so on.