从 MongoDB 中删除数据
Overview
在本指南中,您将删除 MongoDB 中的数据。
所需的时间:10 分钟
您需要的工具
从将数据插入 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 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来删除数据。
在第 6 行,将 URI 字符串替换为您自己的 Atlas 连接字符串。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Conventions; 3 using MongoDB.Driver; 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 read the fields in camelCase 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 // delete code goes here 16 // amount deleted code goes here 17 18 // class that represents the fields of a document in the 19 // sample_guides.comets collection 20 class Comet { 21 public ObjectId Id { get; set; } 22 public string Name { get; set; } 23 public string OfficialName { get; set; } 24 public double OrbitalPeriod { get; set; } 25 public double Radius { get; set; } 26 public double Mass { get; set; } 27 }
提示
以下为概述,同时介绍了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来删除数据。
在第 15 行,将 URI string替换为您自己的Atlas连接string 。
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 "os" 8 9 "go.mongodb.org/mongo-driver/bson" 10 "go.mongodb.org/mongo-driver/mongo" 11 "go.mongodb.org/mongo-driver/mongo/options" 12 ) 13 14 func main() { 15 uri := "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority" 16 17 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri)) 18 if err != nil { 19 panic(err) 20 } 21 22 defer func() { 23 if err = client.Disconnect(context.TODO()); err != nil { 24 panic(err) 25 } 26 }() 27 28 // database and colletion code goes here 29 // delete code goes here 30 // amount deleted code goes here 31 }
提示
以下为概述,同时介绍了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来删除数据。
在第 13 行,将 URI string替换为您自己的Atlas连接string 。
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.DeleteResult; 6 import com.mongodb.client.model.Filters; 7 8 import org.bson.Document; 9 import org.bson.conversions.Bson; 10 11 public class CrudDelete { 12 public static void main(String[] args) { 13 String uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 14 15 try (MongoClient mongoClient = MongoClients.create(uri)) { 16 // database and collection code goes here 17 // insert code goes here 18 // amount deleted code goes here 19 } 20 } 21 }
提示
以下为概述,同时介绍了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来删除数据。
在第 5 行,将 URI 字符串替换为您自己的 Atlas 连接字符串。
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 // delete code goes here 14 // amount deleted code goes here 15 } finally { 16 // Ensures that the client will close when you finish/error 17 await client.close(); 18 } 19 } 20 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 # delete code goes here 10 # amount deleted 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
集合中的特定文档。
以下示例说明了如何使用查询筛选器删除 orbitalPeriod
大于 5 小于 85 的文档。
// delete code goes here var result = coll.DeleteMany(x => x.OrbitalPeriod > 5 && x.OrbitalPeriod < 85);
1 // delete code goes here 2 filter := bson.D{ 3 {"$and", 4 bson.A{ 5 bson.D{{"orbitalPeriod", bson.D{{"$gt", 5}}}}, 6 bson.D{{"orbitalPeriod", bson.D{{"$lt", 85}}}}, 7 }, 8 }, 9 }
MongoDB Java驱动程序包括构建器,可简化创建查询(和其他操作)的进程。 此处,使用Filters.and
、 Filters.lt
和Filters.gt
构建者来构造查询文档。
1 // delete code goes here 2 Bson filter = Filters.and(Filters.gt("orbitalPeriod", 5), Filters.lt("orbitalPeriod", 85)); 3 DeleteResult result = coll.deleteMany(filter);
// delete code goes here const doc = { orbitalPeriod: { $gt: 5, $lt: 85 } }; const result = await coll.deleteMany(doc);
# delete code goes here doc = { "orbitalPeriod": { "$gt": 5, "$lt": 85 } } result = coll.delete_many(doc)
显示您的结果。
result
包含有关删除操作的一些信息。若要验证已删除的文档,请输出驱动程序删除的文档数量。
// amount deleted code goes here Console.WriteLine($"Number of documents deleted: {result.DeletedCount}");
1 // amount deleted code goes here 2 fmt.Printf("Number of documents deleted: %d", result.DeletedCount)
1 // amount deleted code goes here 2 System.out.println("Number of documents deleted: " +result.getDeletedCount());
// amount deleted code goes here console.log("Number of documents deleted: " + result.deletedCount);
# amount deleted code goes here print("Number of documents deleted: ", result.deleted_count)
检查你的结果。
以下是完整的代码,然后是样本输出。
1 using MongoDB.Bson; 2 using MongoDB.Bson.Serialization.Conventions; 3 using MongoDB.Driver; 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 read the fields in camelCase 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 // delete code goes here 19 var result = coll.DeleteMany(x => x.OrbitalPeriod > 5 && x.OrbitalPeriod < 85); 20 21 // amount deleted code goes here 22 Console.WriteLine($"Number of documents deleted: {result.DeletedCount}"); 23 24 // class that maps to the fields of a document in the sample_guides.comets collection 25 class Comet 26 { 27 public ObjectId Id { get; set; } 28 public string Name { get; set; } 29 public string OfficialName { get; set; } 30 public double OrbitalPeriod { get; set; } 31 public double Radius { get; set; } 32 public double Mass { get; set; } 33 }
Number of documents deleted: 2
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 "os" 8 9 "go.mongodb.org/mongo-driver/bson" 10 "go.mongodb.org/mongo-driver/mongo" 11 "go.mongodb.org/mongo-driver/mongo/options" 12 ) 13 14 func main() { 15 uri := "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority" 16 17 client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri)) 18 if err != nil { 19 panic(err) 20 } 21 22 defer func() { 23 if err = client.Disconnect(context.TODO()); err != nil { 24 panic(err) 25 } 26 }() 27 28 // database and colletion code goes here 29 db := client.Database("sample_guides") 30 coll := db.Collection("comets") 31 32 // delete code goes here 33 filter := bson.D{ 34 {"$and", 35 bson.A{ 36 bson.D{{"orbitalPeriod", bson.D{{"$gt", 5}}}}, 37 bson.D{{"orbitalPeriod", bson.D{{"$lt", 85}}}}, 38 }, 39 }, 40 } 41 42 result, err := coll.DeleteMany(context.TODO(), filter) 43 if err != nil { 44 panic(err) 45 } 46 47 // amount deleted code goes here 48 fmt.Printf("Number of documents deleted: %d", result.DeletedCount) 49 }
Number of documents deleted: 2
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.DeleteResult; 6 import com.mongodb.client.model.Filters; 7 8 import org.bson.Document; 9 import org.bson.conversions.Bson; 10 11 public class CrudDelete { 12 public static void main(String[] args) { 13 String uri = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority"; 14 15 try (MongoClient mongoClient = MongoClients.create(uri)) { 16 // database and collection code goes here 17 MongoDatabase db = mongoClient.getDatabase("sample_guides"); 18 MongoCollection<Document> coll = db.getCollection("comets"); 19 20 // delete code goes here 21 Bson filter = Filters.and(Filters.gt("orbitalPeriod", 5), Filters.lt("orbitalPeriod", 85)); 22 DeleteResult result = coll.deleteMany(filter); 23 24 // amount deleted code goes here 25 System.out.println("Number of documents deleted: " +result.getDeletedCount()); 26 } 27 } 28 }
Number of documents deleted: 2
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 // delete code goes here 17 const doc = { 18 orbitalPeriod: { 19 $gt: 5, 20 $lt: 85 21 } 22 }; 23 24 const result = await coll.deleteMany(doc); 25 26 // amount deleted code goes here 27 console.log("Number of documents deleted: " + result.deletedCount); 28 29 } finally { 30 // Ensures that the client will close when you finish/error 31 await client.close(); 32 } 33 } 34 run().catch(console.dir);
Number of documents deleted: 2
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 # delete code goes here 13 doc = { 14 "orbitalPeriod": { 15 "$gt": 5, 16 "$lt": 85 17 } 18 } 19 result = coll.delete_many(doc) 20 21 # amount deleted code goes here 22 print("Number of documents deleted: ", result.deleted_count) 23 24 # Close the connection to MongoDB when you're done. 25 client.close()
Number of documents deleted: 2
总结
如已完成本指南,那么您已从 MongoDB 中删除数据。
MongoDB 中的 CRUD 操作介绍到此结束。
另请参阅
如需深入了解此处介绍的概念,请参阅以下资源: