Update only a single MongoDB document without deleting any date

MongoDBDatabaseBig Data Analytics

To update only a single document, you need to update a specific data with updateOne(). The updateOne() is used to update a single document within the collection based on the filter.

Let us create a collection with documents −

> db.demo495.insertOne({"FirstName":"Chris","Age":19});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e84adfeb0f3fa88e22790ca")
}
> db.demo495.insertOne({"FirstName":"David","Age":21});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e84ae05b0f3fa88e22790cb")
}
> db.demo495.insertOne({"FirstName":"Bob","Age":26});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e84ae0eb0f3fa88e22790cc")
}
> db.demo495.insertOne({"FirstName":"John","Age":22});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e84ae15b0f3fa88e22790cd")
}

Display all documents from a collection with the help of find() method −

> db.demo495.find();

This will produce the following output −

{ "_id" : ObjectId("5e84adfeb0f3fa88e22790ca"), "FirstName" : "Chris", "Age" : 19 }
{ "_id" : ObjectId("5e84ae05b0f3fa88e22790cb"), "FirstName" : "David", "Age" : 21 }
{ "_id" : ObjectId("5e84ae0eb0f3fa88e22790cc"), "FirstName" : "Bob", "Age" : 26 }
{ "_id" : ObjectId("5e84ae15b0f3fa88e22790cd"), "FirstName" : "John", "Age" : 22 }

Following is the query to use updateOne() and update only a single document −

> db.demo495.updateOne({"FirstName":"David"},{$set: {"Age":23} });
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Display all documents from a collection with the help of find() method −

> db.demo495.find();

This will produce the following output −

{ "_id" : ObjectId("5e84adfeb0f3fa88e22790ca"), "FirstName" : "Chris", "Age" : 19 }
{ "_id" : ObjectId("5e84ae05b0f3fa88e22790cb"), "FirstName" : "David", "Age" : 23 }
{ "_id" : ObjectId("5e84ae0eb0f3fa88e22790cc"), "FirstName" : "Bob", "Age" : 26 }
{ "_id" : ObjectId("5e84ae15b0f3fa88e22790cd"), "FirstName" : "John", "Age" : 22 }
raja
Published on 13-May-2020 09:06:03
Advertisements