在 MongoDB 中更新数据
概述
在本指南中,您将更新文档中的一个字段。
所需时间10分钟
所需资源
A到您的MongoDB部署的连接字符串。
已加载到您的集群中的示例数据集。
已安装的MongoDB驱动程序。
从将数据插入MongoDB中插入的数据。
步骤
连接到您的MongoDB实例。
创建一个类,使其类似于您的集合中的文档。
以下类列出了您的文档将拥有的所有字段名称和数据类型。
1 // class that maps to the fields of a document in the sample_guides.comets collection
2 class 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 }
将您的类自动映射到文档的字段。
在C#中,您将字段映射到类的属性,属性名通常为大写。但是,您应该使用驼峰命名法插入数据。为了使驱动程序自动将字段从大写转换为驼峰命名法,创建一个ConventionPack
并注册 CamelCase
命名约定。
1 // instruct the driver to camelCase the fields in MongoDB 2 var pack = new ConventionPack { new CamelCaseElementNameConvention() }; 3 ConventionRegistry.Register("elementNameConvention", pack, x => true);
验证您的连接代码。
提示
以下是最小化代码的概要,用于连接到MongoDB。您将在接下来的几个步骤中添加代码来插入数据。
在行5,将URI字符串替换为您的自己的Atlas连接字符串。
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // Replace the uri string with your MongoDB deployment's connection string. 5 var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 6 7 // instruct the driver to camelCase the fields in MongoDB 8 var pack = new ConventionPack { new CamelCaseElementNameConvention() }; 9 ConventionRegistry.Register("elementNameConvention", pack, x => true); 10 11 var 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 18 class 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 }
提示
以下是最小化代码的概要,用于连接到MongoDB。您将在接下来的几个步骤中添加代码来插入数据。
在行13,将URI字符串替换为您的自己的Atlas连接字符串。
1 package main 2 3 import ( 4 "context" 5 "log" 6 "os" 7 8 "go.mongodb.org/mongo-driver/mongo" 9 "go.mongodb.org/mongo-driver/mongo/options" 10 ) 11 12 func 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 }
提示
以下是最小化代码的概要,用于连接到MongoDB。您将在接下来的几个步骤中添加代码来插入数据。
在行14,将URI字符串替换为您的自己的Atlas连接字符串。
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import com.mongodb.client.result.UpdateResult; 6 import com.mongodb.client.model.Filters; 7 import com.mongodb.client.model.Updates; 8 9 import org.bson.Document; 10 import org.bson.conversions.Bson; 11 12 public 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 }
提示
以下是最小化代码的概要,用于连接到MongoDB。您将在接下来的几个步骤中添加代码来插入数据。
在行4,将URI字符串替换为您的自己的Atlas连接字符串。
1 const { MongoClient } = require("mongodb"); 2 // Replace the uri string with your MongoDB deployment's connection string. 3 const uri = 4 "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 19 run().catch(console.dir);
提示
以下是最小化代码的概要,用于连接到MongoDB。您将在接下来的几个步骤中添加代码来插入数据。
在行4,将URI字符串替换为您的自己的Atlas连接字符串。
1 from pymongo import MongoClient 2 3 # Replace the uri string with your MongoDB deployment's connection string. 4 uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority" 5 6 client = 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. 13 client.close()
提示
mongodb+srv
请确保您已使用srv
选项安装了PyMongo。
python3 -m pip install "pymongo[srv]"
获取数据库和集合。
切换到您要操作的数据库和集合。在本例中,您将使用sample_guides
数据库和comets
集合。
// database and collection code goes here
var db = client.GetDatabase("sample_guides");
var coll = db.GetCollection<Comet>("comets");
1 // database and colletion code goes here 2 db := client.Database("sample_guides") 3 coll := db.Collection("comets")
1 // database and collection code goes here 2 MongoDatabase db = mongoClient.getDatabase("sample_guides"); 3 MongoCollection<Document> coll = db.getCollection("comets");
// database and collection code goes here const db = client.db("sample_guides"); const coll = db.collection("comets");
# database and collection code goes here db = client.sample_guides coll = db.comets
更新《comets》集合中的所有文档。
在上一篇指南中,您向《comets》集合中插入了文档。现在,您需要对这些文档进行更新。所有字段都是以公制单位表示,除了《radius》字段,它是以英制表示。
以下示例使用更新文档将所有文档中的《radius》字段从公制系统转换为英制系统。
提示
转换
1英里 = 1.60934公里
MongoDB C# 驱动程序包括Builders,这些可以简化查询和其他操作的创建过程。在这里,您使用《Filter.Empty》和《Update.Mul》构建器来构建查询文档和更新文档。
// 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);
1 // database and colletion code goes here 2 db := client.Database("sample_guides") 3 coll := db.Collection("comets") 4 5 // update code goes here 6 filter := bson.D{{}} 7 update := bson.D{{"$mul", bson.D{{"radius", 1.60934}}}} 8 9 result, err := coll.UpdateMany(context.TODO(), filter, update) 10 if err != nil { 11 panic(err) 12 }
MongoDB Java 驱动程序包括Builders,这些可以简化查询(和其他操作)的创建过程。在这里,您使用《Filters.empty》和《Updates.mul》构建器来构建查询文档。
1 // update code goes here 2 Bson filter = Filters.empty(); 3 Bson update = Updates.mul("radius", 1.60934); 4 UpdateResult result = coll.updateMany(filter, update);
// update code goes here const filter = { }; const updateDoc = { $mul: { radius: 1.60934 } }; const result = await coll.updateMany(filter, updateDoc);
# update code goes here doc = { '$mul': {'radius': 1.60934} } result = coll.update_many({}, doc)
显示您的结果。
MongoDB中的许多写操作返回一个包含操作信息的结果对象。
对于更新操作,结果对象将包含成功更新的文档修改计数。在这里,您访问此属性并打印它们。
// display the results of your operation Console.WriteLine($"Number of documents updated: {result.ModifiedCount}");
1 // display the results of your operation 2 fmt.Printf("Number of documents updated: %d", result.ModifiedCount)
1 // display the results of your operation 2 System.out.println("Number of documents updated: " + result.getModifiedCount());
// display the results of your operation console.log("Number of documents updated: " + result.modifiedCount);
# display the results of your operation print("Number of documents updated: ", result.modified_count)
检查您的结果。
以下是完整的代码和示例输出。
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 using MongoDB.Bson.Serialization.Conventions; 4 5 // Replace the uri string with your MongoDB deployment's connection string. 6 var uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 7 8 // instruct the driver to camelCase the fields in MongoDB 9 var pack = new ConventionPack { new CamelCaseElementNameConvention() }; 10 ConventionRegistry.Register("elementNameConvention", pack, x => true); 11 12 var client = new MongoClient(uri); 13 14 // database and collection code goes here 15 var db = client.GetDatabase("sample_guides"); 16 var coll = db.GetCollection<Comet>("comets"); 17 18 // update code goes here 19 var filter = Builders<Comet>.Filter.Empty; 20 var update = Builders<Comet>.Update.Mul("radius", 1.60934); 21 var result = coll.UpdateMany(filter, update); 22 23 // display the results of your operation 24 Console.WriteLine($"Number of documents updated: {result.ModifiedCount}"); 25 26 // class that maps to the fields of a document in the sample_guides.comets collection 27 class 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
1 package main 2 3 import ( 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 12 func 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
1 import com.mongodb.client.MongoClient; 2 import com.mongodb.client.MongoClients; 3 import com.mongodb.client.MongoCollection; 4 import com.mongodb.client.MongoDatabase; 5 import com.mongodb.client.result.UpdateResult; 6 import com.mongodb.client.model.Filters; 7 import com.mongodb.client.model.Updates; 8 9 import org.bson.Document; 10 import org.bson.conversions.Bson; 11 12 public 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
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = 5 "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 6 7 const client = new MongoClient(uri); 8 9 async 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 } 33 run().catch(console.dir);
Number of documents updated: 3
1 from pymongo import MongoClient 2 3 # Replace the uri string with your MongoDB deployment's connection string. 4 uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority" 5 6 client = MongoClient(uri) 7 8 # database and collection code goes here 9 db = client.sample_guides 10 coll = db.comets 11 12 # update code goes here 13 doc = {"$mul": {"radius": 1.60934}} 14 result = coll.update_many({}, doc) 15 16 # display the results of your operation 17 print("Number of documents updated: ", result.modified_count) 18 19 # Close the connection to MongoDB when you're done. 20 client.close()
Number of documents updated: 3
摘要
如果您已经完成本指南,您已在MongoDB中更新了数据。
在下一次指南中,您将学习如何在MongoDB中删除文档。
另请参阅
查看以下资源,以获取关于此处展示的概念的更深入信息