Docs Menu
Docs Home
/
Start with Guides

Update Data in MongoDB

In this guide, you will update a field in a document.

Time required: 10 minutes

  • A connection string to your MongoDB deployment.

  • Sample datasets loaded into your cluster.

  • An installed MongoDB Driver.

1
1

The following class lists all the field names and types that your document will have.

CrudUpdate.cs
1// class that maps to the fields of a document in the sample_guides.comets collection
2class Comet {
3 public ObjectId Id { get; set; }
4 public string Name { get; set; }
5 public string OfficialName { get; set; }
6 public double OrbitalPeriod { get; set; }
7 public double Radius { get; set; }
8 public double Mass { get; set; }
9}
2

In C#, you map fields to class properties, which are uppercase by convention. However, you should insert the data with camel case fields. To make the driver automatically convert the fields from uppercase to camel case, create a ConventionPack and register the naming convention for CamelCase.

CrudUpdate.cs
1// instruct the driver to camelCase the fields in MongoDB
2var pack = new ConventionPack { new CamelCaseElementNameConvention() };
3ConventionRegistry.Register("elementNameConvention", pack, x => true);
3

Tip

The following is an outline with the minimum code necessary to connect to MongoDB. You'll make additions over the next few steps to insert data.

At line 5, replace the URI string with your own Atlas connection string.

CrudUpdate.cs
1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// Replace the uri string with your MongoDB deployment's connection string.
5var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
6
7// instruct the driver to camelCase the fields in MongoDB
8var pack = new ConventionPack { new CamelCaseElementNameConvention() };
9ConventionRegistry.Register("elementNameConvention", pack, x => true);
10
11var client = new MongoClient(uri);
12
13// database and collection code goes here
14// update code goes here
15// amount updated code goes here
16
17// class that maps to the fields of a document in the sample_guides.comets collection
18class Comet
19{
20 public ObjectId Id { get; set; }
21 public string Name { get; set; }
22 public string OfficialName { get; set; }
23 public double OrbitalPeriod { get; set; }
24 public double Radius { get; set; }
25 public double Mass { get; set; }
26}

Tip

The following is an outline with the minimum code necessary to connect to MongoDB. You'll make additions over the next few steps to insert data.

At line 13, replace the URI string with your own Atlas connection string.

crud-update.go
1package main
2
3import (
4 "context"
5 "log"
6 "os"
7
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10)
11
12func main() {
13 uri := "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"
14
15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
16 if err != nil {
17 panic(err)
18 }
19
20 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
21 if err != nil {
22 panic(err)
23 }
24 defer func() {
25 if err = client.Disconnect(context.TODO()); err != nil {
26 panic(err)
27 }
28 }()
29
30 // database and colletion code goes here
31 // update code goes here
32 // amount update code goes here
33}

Tip

The following is an outline with the minimum code necessary to connect to MongoDB. You'll make additions over the next few steps to insert data.

At line 14, replace the URI string with your own Atlas connection string.

CrudUpdate.java
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import com.mongodb.client.result.UpdateResult;
6import com.mongodb.client.model.Filters;
7import com.mongodb.client.model.Updates;
8
9import org.bson.Document;
10import org.bson.conversions.Bson;
11
12public class CrudUpdate {
13 public static void main(String[] args) {
14 String uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
15
16 try (MongoClient mongoClient = MongoClients.create(uri)) {
17 // database and collection code goes here
18 // update code goes here
19 // amount updated code goes here
20 }
21 }
22}

Tip

The following is an outline with the minimum code necessary to connect to MongoDB. You'll make additions over the next few steps to insert data.

At line 4, replace the URI string with your own Atlas connection string.

crud-update.js
1const { MongoClient } = require("mongodb");
2// Replace the uri string with your MongoDB deployment's connection string.
3const uri =
4 "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 await client.connect();
11 // database and collection code goes here
12 // update code goes here
13 // amount deleted code goes here
14 } finally {
15 // Ensures that the client will close when you finish/error
16 await client.close();
17 }
18}
19run().catch(console.dir);

Tip

The following is an outline with the minimum code necessary to connect to MongoDB. You'll make additions over the next few steps to insert data.

At line 4, replace the URI string with your own Atlas connection string.

crud_update.py
1from pymongo import MongoClient
2
3# Replace the uri string with your MongoDB deployment's connection string.
4uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"
5
6client = MongoClient(uri)
7
8# database and collection code goes here
9# update code goes here
10# amount updated code goes here
11
12# Close the connection to MongoDB when you're done.
13client.close()

Tip

mongodb+srv

Make sure you've installed PyMongo with the srv option.

python3 -m pip install "pymongo[srv]"
2

Switch to the database and collection you wish to work with. In this case you will be using the sample_guides database and comets collection.

CrudUpdate.cs
// database and collection code goes here
var db = client.GetDatabase("sample_guides");
var coll = db.GetCollection<Comet>("comets");
crud-update.go
1// database and colletion code goes here
2db := client.Database("sample_guides")
3coll := db.Collection("comets")
CrudUpdate.java
1// database and collection code goes here
2MongoDatabase db = mongoClient.getDatabase("sample_guides");
3MongoCollection<Document> coll = db.getCollection("comets");
crud-update.js
// database and collection code goes here
const db = client.db("sample_guides");
const coll = db.collection("comets");
crud_update.py
# database and collection code goes here
db = client.sample_guides
coll = db.comets
3

In the previous guide, you inserted documents into the comets collection. Now, you have a requirement to update those documents. All fields are in metric units except for the radius, which is in imperial.

The following example uses an update document to convert the radius field from the metric system to the imperial system in all documents.

Tip

Conversion

1 mile = 1.60934 kilometers

The MongoDB C# Driver includes Builders that simplify the process of creating queries and other operations. Here, you use the Filter.Empty and Update.Mul builders to construct the query document and update document.

CrudUpdate.cs
// update code goes here
var filter = Builders<Comet>.Filter.Empty;
var update = Builders<Comet>.Update.Mul("radius", 1.60934);
var result = coll.UpdateMany(filter, update);
crud-update.go
1// database and colletion code goes here
2db := client.Database("sample_guides")
3coll := db.Collection("comets")
4
5// update code goes here
6filter := bson.D{{}}
7update := bson.D{{"$mul", bson.D{{"radius", 1.60934}}}}
8
9result, err := coll.UpdateMany(context.TODO(), filter, update)
10if err != nil {
11 panic(err)
12}

The MongoDB Java Driver includes Builders that simplify the process of creating queries (and other operations). Here, you use the Filters.empty and Updates.mul builders to construct the query document.

CrudUpdate.java
1// update code goes here
2Bson filter = Filters.empty();
3Bson update = Updates.mul("radius", 1.60934);
4UpdateResult result = coll.updateMany(filter, update);
crud-update.js
// update code goes here
const filter = { };
const updateDoc = {
$mul: {
radius: 1.60934
}
};
const result = await coll.updateMany(filter, updateDoc);
crud_update.py
# update code goes here
doc = {
'$mul': {'radius': 1.60934}
}
result = coll.update_many({}, doc)
4

Many write operations in MongoDB return a result object that contains information about the operation.

For update operations, the result object will contain the modified count of documents the driver successfully updated. Here, you access this property and print them.

CrudUpdate.cs
// display the results of your operation
Console.WriteLine($"Number of documents updated: {result.ModifiedCount}");
crud-update.go
1// display the results of your operation
2fmt.Printf("Number of documents updated: %d", result.ModifiedCount)
CrudUpdate.java
1// display the results of your operation
2System.out.println("Number of documents updated: " + result.getModifiedCount());
crud-update.js
// display the results of your operation
console.log("Number of documents updated: " + result.modifiedCount);
crud_update.py
# display the results of your operation
print("Number of documents updated: ", result.modified_count)
5

Here is the complete code followed by sample output.

CrudUpdate.cs
1using MongoDB.Bson;
2using MongoDB.Driver;
3using MongoDB.Bson.Serialization.Conventions;
4
5// Replace the uri string with your MongoDB deployment's connection string.
6var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
7
8// instruct the driver to camelCase the fields in MongoDB
9var pack = new ConventionPack { new CamelCaseElementNameConvention() };
10ConventionRegistry.Register("elementNameConvention", pack, x => true);
11
12var client = new MongoClient(uri);
13
14// database and collection code goes here
15var db = client.GetDatabase("sample_guides");
16var coll = db.GetCollection<Comet>("comets");
17
18// update code goes here
19var filter = Builders<Comet>.Filter.Empty;
20var update = Builders<Comet>.Update.Mul("radius", 1.60934);
21var result = coll.UpdateMany(filter, update);
22
23// display the results of your operation
24Console.WriteLine($"Number of documents updated: {result.ModifiedCount}");
25
26// class that maps to the fields of a document in the sample_guides.comets collection
27class Comet
28{
29 public ObjectId Id { get; set; }
30 public string Name { get; set; }
31 public string OfficialName { get; set; }
32 public double OrbitalPeriod { get; set; }
33 public double Radius { get; set; }
34 public double Mass { get; set; }
35}
Number of documents updated: 3
crud-update.go
1package main
2
3import (
4 "context"
5 "fmt"
6
7 "go.mongodb.org/mongo-driver/bson"
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10)
11
12func main() {
13 uri := "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"
14
15 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
16 if err != nil {
17 panic(err)
18 }
19
20 defer func() {
21 if err = client.Disconnect(context.TODO()); err != nil {
22 panic(err)
23 }
24 }()
25
26 // database and colletion code goes here
27 db := client.Database("sample_guides")
28 coll := db.Collection("comets")
29
30 // update code goes here
31 filter := bson.D{{}}
32 update := bson.D{{"$mul", bson.D{{"radius", 1.60934}}}}
33
34 result, err := coll.UpdateMany(context.TODO(), filter, update)
35 if err != nil {
36 panic(err)
37 }
38
39 // display the results of your operation
40 fmt.Printf("Number of documents updated: %d", result.ModifiedCount)
41}
Number of documents updated: 3
CrudUpdate.java
1import com.mongodb.client.MongoClient;
2import com.mongodb.client.MongoClients;
3import com.mongodb.client.MongoCollection;
4import com.mongodb.client.MongoDatabase;
5import com.mongodb.client.result.UpdateResult;
6import com.mongodb.client.model.Filters;
7import com.mongodb.client.model.Updates;
8
9import org.bson.Document;
10import org.bson.conversions.Bson;
11
12public class CrudUpdate {
13 public static void main(String[] args) {
14 String uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
15
16 try (MongoClient mongoClient = MongoClients.create(uri)) {
17 // database and collection code goes here
18 MongoDatabase db = mongoClient.getDatabase("sample_guides");
19 MongoCollection<Document> coll = db.getCollection("comets");
20
21 // update code goes here
22 Bson filter = Filters.empty();
23 Bson update = Updates.mul("radius", 1.60934);
24 UpdateResult result = coll.updateMany(filter, update);
25
26 // display the results of your operation
27 System.out.println("Number of documents updated: " + result.getModifiedCount());
28 }
29 }
30}
Number of documents updated: 3
crud-update.js
1const { MongoClient } = require("mongodb");
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri =
5 "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
6
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11 await client.connect();
12 // database and collection code goes here
13 const db = client.db("sample_guides");
14 const coll = db.collection("comets");
15
16 // update code goes here
17 const filter = {};
18 const updateDoc = {
19 $mul: {
20 radius: 1.60934,
21 },
22 };
23
24 const result = await coll.updateMany(filter, updateDoc);
25
26 // display the results of your operation
27 console.log("Number of documents updated: " + result.modifiedCount);
28 } finally {
29 // Ensures that the client will close when you finish/error
30 await client.close();
31 }
32}
33run().catch(console.dir);
Number of documents updated: 3
crud_update.py
1from pymongo import MongoClient
2
3# Replace the uri string with your MongoDB deployment's connection string.
4uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"
5
6client = MongoClient(uri)
7
8# database and collection code goes here
9db = client.sample_guides
10coll = db.comets
11
12# update code goes here
13doc = {"$mul": {"radius": 1.60934}}
14result = coll.update_many({}, doc)
15
16# display the results of your operation
17print("Number of documents updated: ", result.modified_count)
18
19# Close the connection to MongoDB when you're done.
20client.close()
Number of documents updated: 3

If you have completed this guide, you have updated data in MongoDB.

In the next guide, you will delete documents from MongoDB.

See the following resources for more in-depth information about the concepts presented here:

What's Next
Delete Data from MongoDB
10 mins

Specify which documents to delete from MongoDB.

Start Guide
Chapter 2
CRUD
  • Add a MongoDB Driver
  • Read Data in MongoDB
  • Read Data from MongoDB With Queries
  • Read Data using Operators and Compound Queries
  • Insert Data into MongoDB
  • Update Data in MongoDB
  • Delete Data from MongoDB