Docs 菜单
Docs 主页
/
入门指南

从 MongoDB 中删除数据

在本指南中,您将删除 MongoDB 中的数据。

所需的时间:10 分钟

  • stringMongoDB部署的 连接 。

  • 加载到集群中的示例数据集。

  • 已安装的 MongoDB 驱动程序

1
1

以下类列出了文档将具有的所有字段名称和类型。

CrudDelete.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

在C#中,将字段映射到类属性,按照惯例,类属性为大写。 但是,应删除具有混合使用大小写字段的数据。 要使驾驶员自动将字段从大写转换为驼峰式大小写,请创建 ConventionPack并注册CamelCase的命名约定。

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

提示

以下为概述,同时介绍了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来删除数据。

在第 6 行,将 URI 字符串替换为您自己的 Atlas 连接字符串

CrudDelete.cs
1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Conventions;
3using MongoDB.Driver;
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 read the fields in camelCase
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
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
20class 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 。

crud-delete.go
1package main
2
3import (
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
14func 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 。

CrudDelete.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.DeleteResult;
6import com.mongodb.client.model.Filters;
7
8import org.bson.Document;
9import org.bson.conversions.Bson;
10
11public 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 连接字符串

crud-delete.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 // 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}
20run().catch(console.dir);

提示

以下为概述,同时介绍了连接到 MongoDB 所需的最少代码。在接下来的几个步骤中,您将添加更多内容来删除数据。

在第 4 行,将 URI 字符串替换为您自己的 Atlas 连接字符串

crud_delete.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# delete code goes here
10# amount deleted code goes here
11
12# Close the connection to MongoDB when you're done.
13client.close()

提示

mongodb+srv

确保您已安装带 srv 选项的 PyMongo。

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

切换到要查询的数据库和集合。在本例中,您将使用 sample_guides 数据库和 comets 集合。

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

以下示例说明了如何使用查询筛选器删除 orbitalPeriod 大于 5 小于 85 的文档。

CrudDelete.cs
// delete code goes here
var result = coll.DeleteMany(x => x.OrbitalPeriod > 5 && x.OrbitalPeriod < 85);
crud-delete.go
1// delete code goes here
2filter := 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.andFilters.ltFilters.gt构建者来构造查询文档。

CrudDelete.java
1// delete code goes here
2Bson filter = Filters.and(Filters.gt("orbitalPeriod", 5), Filters.lt("orbitalPeriod", 85));
3DeleteResult result = coll.deleteMany(filter);
crud-delete.js
// delete code goes here
const doc = {
orbitalPeriod: {
$gt: 5,
$lt: 85
}
};
const result = await coll.deleteMany(doc);
crud_delete.py
# delete code goes here
doc = {
"orbitalPeriod": {
"$gt": 5,
"$lt": 85
}
}
result = coll.delete_many(doc)
4

result 包含有关删除操作的一些信息。若要验证已删除的文档,请输出驱动程序删除的文档数量。

CrudDelete.cs
// amount deleted code goes here
Console.WriteLine($"Number of documents deleted: {result.DeletedCount}");
crud-delete.go
1// amount deleted code goes here
2fmt.Printf("Number of documents deleted: %d", result.DeletedCount)
CrudDelete.java
1// amount deleted code goes here
2System.out.println("Number of documents deleted: " +result.getDeletedCount());
crud-delete.js
// amount deleted code goes here
console.log("Number of documents deleted: " + result.deletedCount);
crud_delete.py
# amount deleted code goes here
print("Number of documents deleted: ", result.deleted_count)
5

以下是完整的代码,然后是样本输出。

CrudDelete.cs
1using MongoDB.Bson;
2using MongoDB.Bson.Serialization.Conventions;
3using MongoDB.Driver;
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 read the fields in camelCase
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// delete code goes here
19var result = coll.DeleteMany(x => x.OrbitalPeriod > 5 && x.OrbitalPeriod < 85);
20
21// amount deleted code goes here
22Console.WriteLine($"Number of documents deleted: {result.DeletedCount}");
23
24// class that maps to the fields of a document in the sample_guides.comets collection
25class 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
crud-delete.go
1package main
2
3import (
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
14func 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
CrudDelete.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.DeleteResult;
6import com.mongodb.client.model.Filters;
7
8import org.bson.Document;
9import org.bson.conversions.Bson;
10
11public 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
crud-delete.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 // 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}
34run().catch(console.dir);
Number of documents deleted: 2
crud_delete.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# delete code goes here
13doc = {
14 "orbitalPeriod": {
15 "$gt": 5,
16 "$lt": 85
17 }
18}
19result = coll.delete_many(doc)
20
21# amount deleted code goes here
22print("Number of documents deleted: ", result.deleted_count)
23
24# Close the connection to MongoDB when you're done.
25client.close()
Number of documents deleted: 2

如已完成本指南,那么您已从 MongoDB 中删除数据。

MongoDB 中的 CRUD 操作介绍到此结束。

如需深入了解此处介绍的概念,请参阅以下资源:

接下来的步骤
构建动态索引
5 分钟

使用全文搜索在 MongoDB 中检索文档。

入门指南
第 3 章
Atlas Search
  • 构建动态索引
  • 使用静态字段映射建立索引
  • 使用复合运算符查询
  • 使用分面进行查询