Docs Menu
Docs Home
/
Start with Guides

Delete Data from MongoDB

In this guide, you will delete data from MongoDB.

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.

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

In C#, you map fields to class properties, which are uppercase by convention. However, you should delete 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.

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

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 delete data.

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

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}

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 delete data.

At line 15, replace the URI string with your own Atlas connection 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}

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 delete data.

At line 13, replace the URI string with your own Atlas connection 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}

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 delete data.

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

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);

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 delete data.

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

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()

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 query. In this case you will be using the sample_guides database and comets collection.

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

The following example illustrates using a query filter to delete documents where their orbitalPeriod is greater than 5 and less than 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}

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

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

The result contains some information about the delete operation. To verify you deleted documents, print the amount of documents the driver deleted.

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

Here is the complete code followed by sample output.

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

If you have completed this guide, you have deleted data from MongoDB.

That completes this introduction to CRUD operations in MongoDB.

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

What's Next
Build a Dynamic Index
5 mins

Retrieve documents in MongoDB with full-text search.

Start Guide
Chapter 3
Atlas Search
  • Build a Dynamic Index
  • Build an Index with Static Field Mappings
  • Querying with the Compound Operator
  • Querying with Facets

Next

Start with Guides