Overview
In this guide, you can learn how to remove documents from your MongoDB collections using delete operations.
Sample Data
The example in this guide uses the following Book
struct as a model for documents
in the books
collection:
type Book struct { Title string Author string Length int32 }
To run the example in this guide, load the sample data into the
db.books
collection with the following snippet:
coll := client.Database("db").Collection("books") docs := []interface{}{ Book{Title: "Atonement", Author: "Ian McEwan", Length: 351}, Book{Title: "My Brilliant Friend", Author: "Elena Ferrante", Length: 331}, Book{Title: "Lucy", Author: "Jamaica Kincaid", Length: 103}, Book{Title: "Outline", Author: "Rachel Cusk", Length: 258}, } result, err := coll.InsertMany(context.TODO(), docs)
Each document contains a description of a book that
includes the title, author, and page length corresponding to
the title
, author
, and length
fields in each document.
Tip
Nonexistent Databases and Collections
If the necessary database and collection don't exist when you perform a write operation, the server implicitly creates them.
Delete Operations
Use delete operations to remove data from MongoDB. Delete operations consist of the following methods:
DeleteOne()
, which deletes the first document that matches the filterDeleteMany()
, which deletes all documents that match the filter
Tip
If one document matches your filter when running the DeleteMany()
method, it's equivalent to running the DeleteOne()
method.
Parameters
The DeleteOne()
and DeleteMany()
methods expect you to pass a
Context
type and a non-nil
query filter specifying which
documents to match.
They both optionally take a DeleteOptions
type as a third parameter,
which represents options you can use to configure the delete operation.
If you don't specify a DeleteOptions
, the driver uses the default
values for each option.
The DeleteOptions
type allows you to configure options with the
following methods:
Method | Description |
---|---|
| The index to use to scan for documents to delete. Default: nil |
| The type of language collation to use when sorting results. Default: nil |
Return Value
The DeleteOne()
and DeleteMany()
methods return a
DeleteResult
type. This type contains the DeletedCount
property,
which states the number of documents deleted. If there are no matches to
your filter, no document gets deleted and DeletedCount
is 0
.
Example
The following example performs the following with the DeleteMany()
method:
Matches and deletes documents where the
length
is greater than300
Instructs the method to use the
_id
as the index
filter := bson.D{{"length", bson.D{{"$gt", 300}}}} opts := options.Delete().SetHint(bson.D{{"_id", 1}}) result, err := coll.DeleteMany(context.TODO(), filter, opts) if err != nil { panic(err) } fmt.Printf("Number of documents deleted: %d\n", result.DeletedCount)
Number of documents deleted: 2
Tip
If the preceding example used the DeleteOne()
method instead of
DeleteMany()
, the driver would delete the first of the two
matched documents.
DeleteOne() Example: Full File
Note
Example Setup
This example connects to an instance of MongoDB by using a
connection URI. To learn more about connecting to your MongoDB
instance, see the Create a MongoClient guide. This example
also uses the restaurants
collection in the sample_restaurants
database
included in the Atlas sample datasets. You
can load them into your database on the free tier of MongoDB Atlas
by following the Get Started with Atlas Guide.
The following example is a fully runnable file that finds and deletes an
existing document in the restaurants
collection.
// Deletes a document from a collection by using the Go driver package main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) // Defines a Restaurant struct as a model for documents in the "restaurants" collection type Restaurant struct { ID bson.ObjectID `bson:"_id"` Name string `bson:"name"` Cuisine string `bson:"cuisine,omitempty"` Address interface{} `bson:"address,omitempty"` Borough string `bson:"borough,omitempty"` Grades []interface{} `bson:"grades,omitempty"` } func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() coll := client.Database("sample_restaurants").Collection("restaurants") filter := bson.D{{"name", "New Corner"}} // Deletes the first document that has a "name" value of "New Corner" result, err := coll.DeleteOne(context.TODO(), filter) // Prints a message if any errors occur during the operation if err != nil { panic(err) } // Prints the number of deleted documents fmt.Printf("Documents deleted: %d\n", result.DeletedCount) // When you run this file for the first time, it prints output similar to the following: // Documents deleted: 1 }
Documents deleted: 1
DeleteMany() Example: Full File
Note
Example Setup
This example connects to an instance of MongoDB by using a
connection URI. To learn more about connecting to your MongoDB
instance, see the Create a MongoClient guide. This example
also uses the restaurants
collection in the sample_restaurants
database
included in the Atlas sample datasets. You
can load them into your database on the free tier of MongoDB Atlas
by following the Get Started with Atlas Guide.
The following example is a fully runnable file that performs the following
actions on the restaurants
collection:
Matches and deletes documents where the
cuisine
field value isGerman
and theborough
field value isQueens
Deletes all matching documents
// Deletes multiple documents from a collection by using the Go driver package main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) // Defines a Restaurant struct as a model for documents in the "restaurants" collection type Restaurant struct { ID bson.ObjectID `bson:"_id"` Name string `bson:"name"` Borough string `bson:"borough"` Cuisine string `bson:"cuisine"` } func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() coll := client.Database("sample_restaurants").Collection("restaurants") filter := bson.D{ {"borough", "Queens"}, {"cuisine", "German"}, } // Deletes all documents that have a "Borough" value of "Queens" and a "Cuisine" value of "German" results, err := coll.DeleteMany(context.TODO(), filter) if err != nil { panic(err) } // Prints the number of deleted documents fmt.Printf("Documents deleted: %d\n", results.DeletedCount) // When you run this file for the first time, it prints output similar to the following: // Documents deleted: 6 }
Documents deleted: 6
Additional Information
To learn more about performing the operations mentioned, see the following guides:
To learn about how the driver uses Context, see Context Package.
To learn more about specifying hints, see Indexes.
To learn more about collations, see Collations.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: