Delete Data from MongoDB
Overview
In this guide, you will delete data from MongoDB.
Time required: 10 minutes
What You'll Need
A connection string to your MongoDB deployment.
Sample datasets loaded into your cluster.
Data inserted from the Insert Data into MongoDB guide.
Procedure
Connect to your MongoDB instance.
Create a class that resembles a document from your collection.
The following class lists all the field names and types that your document will have.
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 }
Automap your class to the documents fields.
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
.
1 // instruct the driver to camelCase the fields in MongoDB 2 var pack = new ConventionPack { new CamelCaseElementNameConvention() }; 3 ConventionRegistry.Register("elementNameConvention", pack, x => true);
Verify your connection code.
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.
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 }
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.
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 }
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.
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 }
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.
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);
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.
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()
Tip
mongodb+srv
Make sure you've installed PyMongo with the srv
option.
python3 -m pip install "pymongo[srv]"
Get the database and collection.
Switch to the database and collection you wish to query. In
this case you will be using the sample_guides
database and
comets
collection.
// 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
Delete specific documents in the comets
collection.
The following example illustrates using a query filter to delete
documents where their orbitalPeriod
is greater than 5 and less
than 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 }
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.
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)
Display your results.
The result
contains some information about the delete
operation. To verify you deleted documents, print the amount of
documents the driver deleted.
// 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)
Check your results.
Here is the complete code followed by sample output.
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
Summary
If you have completed this guide, you have deleted data from MongoDB.
That completes this introduction to CRUD operations in MongoDB.
See Also
See the following resources for more in-depth information about the concepts presented here:
The MongoDB C# Driver documentation
The MongoDB Go Driver documentation
The MongoDB Java(Sync) Driver documentation
The MongoDB Node.js Driver documentation
Retrieve documents in MongoDB with full-text search.