How to Delete MongoDB Documents using the Golang Driver

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

This tutorial will cover two methods used to delete MongoDB documents with the Golang driver. These two methods used to delete MongoDB documents with the Golang driver include the DeleteOne()method and DeleteMany() API calls method. These two methods are used to delete just a single record or a number of documents, respectively.

Prerequisites Needed to Delete MongoDB Documents with the Golang Driver

  • The MongoDB process must be properly installed on the server running the Golang scripts in order to execute the API calls. Execute the mongod command in a terminal window to confirm the service is running. The results should resemble the following:

Screenshot of a terminal window using mongod command to check the MongoDB processes and PID

  • Golang must be installed and the $GOPATH set on the server executing the API calls to MongoDB.

  • Confirm Golang is properly installed and setup by executing the go version and $GOPATH commands.

NOTE: Create the MongoDB script in the same directory as the $GOPATH if the MongoDB project is to be used as a source Go-code and imported into other scripts.

How to Create a New Golang Script for the MongoDB Project

First, navigate to the project’s folder in a terminal window and create a new Golang script using the following touch command:

1
touch delete_docs.go

Now edit the Golang script with an IDE that supports Golang or use a terminal-based editor like Nano or Vim to edit the .go script.

How to Declare a Package Main() and Import the MongoDB Packages

At the beginning of the Golang script, declare the main() function using Golang’s package statement and import all of the libraries necessary for deleting MongoDB documents using the following script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main

import (
"context" // Manage multiple requests
"fmt" // Println() function
"log" // Log errors to terminal
"reflect" // Get an object type
"time"

// Import the BSON libraries for MongoDB
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"

// Import the 'mongo-driver' package libraries
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

How to Declare the Main( ) Golang Function and Connect to MongoDB

The following is an example of how to instantiate the driver’s client with some options passed to connect to the MongoDB server:

1
2
3
4
5
6
7
8
9
10
11
func main() {

// Declare host and port options to pass to the Connect() method
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
fmt.Println("clientOptions type:", reflect.TypeOf(clientOptions))

// Connect to the MongoDB and return Client instance
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal("Error calling mongo.Connect():", err)
}

How to declare a context object and instances of the MongoDB database and collection

Execute the below script to declare a context object for the MongoDB API calls and pass string values to the client’s object’s Database().Collection() method calls so Golang can tell what collection to delete the documents from:

1
2
3
4
5
6
7
8
9
// Declare Context type object for managing multiple API requests
ctx, _ := context.WithTimeout(context.Background(), 15*time.Second)

// Declare an instance of the database and collection
db := client.Database("SomeDatabase")
col := db.Collection("Some Collection")

// *mongo.DeleteResult object returned by API call
fmt.Println("Collection type:", reflect.TypeOf(col), "n")

The Collection() method call will return a  *mongo.Collection object that can be used to make API calls. If the collection doesn’t exist, or if the string used for the collection or database name is incorrect, the API calls will always return a result indicating that no documents were deleted.

How to Call the DeleteOne( ) API Method in Golang

The DeleteOne() method is used for deleting a single MongoDB document in Golang. This method will delete only the first document from the collection that matches the filter, regardless of how many documents match the filter query passed to the method call.

How to delete a MongoDB document matching a BSON object ID

Declare a new BSON object by passing a string of the targeted ID to the primitive package library’s ObjectIDFromHex() API call by executing the following script:

1
2
3
4
5
// Declare a primitive ObjectID from a hexadecimal string
idPrimitive, err := primitive.ObjectIDFromHex("5d36277e024f042ff4837ad5")
if err != nil {
log.Fatal("primitive.ObjectIDFromHex ERROR:", err)
} else {

The above example will log any API errors and exit the script if the method call failed to instantiate a Golang primitive instance of the BSON object ID.

How to call the MongoDB client’s DeleteOne() method if no errors were returned

Pass the context object instantiated earlier as the method call’s first argument. When passing the primitive object, instantiated from the string to the method, make sure the primitive object is nested inside a bson.M (BSON map) object with _id as the map’s key using the following script:

1
2
3
4
5
6
7
// Call the DeleteOne() method by passing BSON
res, err := col.DeleteOne(ctx, bson.M{"_id": idPrimitive})
fmt.Println("DeleteOne Result TYPE:", reflect.TypeOf(res))

if err != nil {
log.Fatal("DeleteOne() ERROR:", err)
} else {

How to print the results of the DeleteOne() API call to MongoDB

Even if no documents were deleted, the method call should have returned a *mongo.DeleteResult object. Execute the following result object’s DeletedCount attribute to evaluate if there was a document in the collection that matched the BSON ID string from earlier:

1
2
3
4
5
6
7
8
9
10
11
12
// Check if the response is 'nil'
if res.DeletedCount == 0 {
fmt.Println("DeleteOne() document not found:", res)
} else {
// Print the results of the DeleteOne() method
fmt.Println("DeleteOne Result:", res)

// *mongo.DeleteResult object returned by API call
fmt.Println("DeleteOne TYPE:", reflect.TypeOf(res))
}
}
}

As the method call is DeleteOne(), the value of the result object’sDeletedCount attribute should be either 0 or 1, depending on if the ID passed to the method matches any documents on the collection.

How to Delete Multiple MongoDB Documents in Golang Using the DeleteMany() Method

The DeleteMany()Golang method call is used for deleting multiple documents from a MongoDB collection by passing a nested bson.M object as the second parameter to the API call.

How to declare a BSON object for the DeleteMany() method’s filter

The field name in the outer key of the nested BSON map object must match a field for some documents in the MongoDB collection. Execute the following command to pass a string operator as the inner BSON object’s key:

1
2
// BSON filter for all documents with a value of 1
f := bson.M{"int field": bson.M{"$eq": 1}}

How to call the Golang driver’s DeleteMany() method to delete multiple MongoDB documents

Execute the following script to pass a context object and the nested BSON filter to the DeleteMany() method and have it return a *mongo.DeleteResult object:

1
2
3
4
5
6
7
fmt.Println("nDeleting documents with filter:", f)

// Call the DeleteMany() method to delete docs matching filter
res, err := col.DeleteMany(ctx, f)

// *mongo.DeleteResult object returned by API call
fmt.Println("DeleteMany() result TYPE:", reflect.TypeOf(res))

How to check if the DeleteMany() Golang method returned any MongoDB API errors

Evaluate the API call’s error object using the same procedure as with the DeleteOne() call. The err object should have a value of nil if the parameters were passed properly. If there are no errors, evaluate the result object’s DeletedCount integer value to assess if any documents were actually deleted using the following script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Check for DeleteMany() API errors
if err != nil {
log.Fatal("DeleteMany() ERROR:", err)
} else {

// Check if the response is 'nil'
if res.DeletedCount == 0 {
fmt.Println("DeleteMany() documents not found:", res)
} else {
// Print the result of DeleteMany()
fmt.Printf("DeleteMany() TOTAL: %d", res.DeletedCount)
fmt.Println("nDeleteMany() result:", res)
}
}
}

Employ Golang’s go run command to execute the script and the results of the Golang API calls to the MongoDB server. This will print out a response resembling the following, provided no documents matched the filter:

1
2
3
4
5
6
7
8
9
clientOptions type: *options.ClientOptions
Collection type: *mongo.Collection

DeleteOne Result TYPE: *mongo.DeleteResult
DeleteOne() document not found: &{0}

Deleting documents with filter: map[int field:map[$eq:1]]
DeleteMany() result TYPE: *mongo.DeleteResult
DeleteMany() documents not found: &{0}

Screenshot of terminal running Go script to delete MongoDB documents in a collection

Conclusion

This tutorial covered how to use the DeleteOne() and DeleteMany() API calls methods to delete MongoDB documents with the Golang driver. The tutorial explained how to create a new Golang script for the MongoDB Project, declare a package main( ) and import the MongoDB packages. The tutorial also covered how to declare a context object and instances of the MongoDB database and collection and how to check if the DeleteMany( ) Golang method returned any MongoDB API errors. Remember that the field name in the outer key of the nested BSON map object must match a field for some documents in the MongoDB collection.

Just the Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main

import (
"context" // Manage multiple requests
"fmt" // Println() function
"log" // Log errors to terminal
"reflect" // Get an object type
"time"

// Import the BSON libraries for MongoDB
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"

// Import the 'mongo-driver' package libraries
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
// Declare host and port options to pass to the Connect() method
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
fmt.Println("clientOptions type:", reflect.TypeOf(clientOptions))

// Connect to the MongoDB and return Client instance
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal("Error calling mongo.Connect():", err)
}

// Declare Context type object for managing multiple API requests
ctx, _ := context.WithTimeout(context.Background(), 15*time.Second)

// Declare an instance of the database and collection
db := client.Database("SomeDatabase")
col := db.Collection("Some Collection")

// *mongo.DeleteResult object returned by API call
fmt.Println("Collection type:", reflect.TypeOf(col), "n")

// Declare a primitive ObjectID from a hexadecimal string
idPrimitive, err := primitive.ObjectIDFromHex("5d36277e024f042ff4837ad5")
if err != nil {
log.Fatal("primitive.ObjectIDFromHex ERROR:", err)
} else {

// Call the DeleteOne() method by passing BSON
res, err := col.DeleteOne(ctx, bson.M{"_id": idPrimitive})
fmt.Println("DeleteOne Result TYPE:", reflect.TypeOf(res))

if err != nil {
log.Fatal("DeleteOne() ERROR:", err)
} else {

// Check if the response is 'nil'
if res.DeletedCount == 0 {
fmt.Println("DeleteOne() document not found:", res)
} else {
// Print the results of the DeleteOne() method
fmt.Println("DeleteOne Result:", res)

// *mongo.DeleteResult object returned by API call
fmt.Println("DeleteOne TYPE:", reflect.TypeOf(res))
}
}
}

// BSON filter for all documents with a value of 1
f := bson.M{"int field": bson.M{"$eq": 1}}
fmt.Println("nDeleting documents with filter:", f)

// Call the DeleteMany() method to delete docs matching filter
res, err := col.DeleteMany(ctx, f)

// *mongo.DeleteResult object returned by API call
fmt.Println("DeleteMany() result TYPE:", reflect.TypeOf(res))

// Check for DeleteMany() API errors
if err != nil {
log.Fatal("DeleteMany() ERROR:", err)
} else {

// Check if the response is 'nil'
if res.DeletedCount == 0 {
fmt.Println("DeleteMany() documents not found:", res)
} else {
// Print the result of DeleteMany()
fmt.Printf("DeleteMany() TOTAL: %d", res.DeletedCount)
fmt.Println("nDeleteMany() result:", res)
}
}
}

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.