MongoDB Method: db.collection.deleteOne()

Summary

Method Namedb.collection.deleteOne()
UsageDelete single document
Group delete

Signature

db.collection.deleteOne(filter, options)

Usage

Delete a single document. We can select document(s) by filter and delete the first one using this method.

NOTES

  • If multiple documents match the filter criteria, then the first one will be deleted.

Arguments

ParameterDescriptionTypeOptional
filteroptions to filter a documentdocument
optionsSome special options for the updatedocumentyes

“options” argument parameters

“options” argument accepts a document, an the following options are allowed in the document.

ParameterDescriptionTypeOptional
writeConcernMention write convern in a documentdocumentyes
collationDefine the collation to be used for this operationdocumentyes
hintIndex to be used for this operationdocument or stringyes

Return Value

Return valueCase for the return value
deleteCountNumber of document
acknowledgedtrue if writeConcert is provided, or false otherwise

NOTES

  • for this deleteOne() method, the value of deleteCount will be one of the following
    • 1 => if the filter matches one or more document and one document was deleted
    • 0 => if the filter does not match any existing document

Examples

Here are a few examples of the method usage-

# MongoDB db.collection.deleteOne() method demo

# Insert some documents
bigboxcode> db.customer.insertMany([
  {
    "name": "Izabella Conroy",
    "age": 19,
    "phone": "108-679-2154",
    "address": {
      "street": "11 North Vineyard Drive",
      "city": "Minneapolis",
      "state": "Minnesota",
      "postalCode": "19426",
      "country": "US"
    },
    "profileCompletenessScore": 30
  },
  {
    "name": "Lambert Purdy",
    "age": 28,
    "phone": "(610) 489-3633",
    "address": {
      "street": "305 2nd Ave",
      "city": "Collegeville",
      "state": "Minnesota",
      "postalCode": "81007",
      "country": "US"
    },
    "profileCompletenessScore": 40
  },
  {
    "name": "Alisa Parker",
    "age": 72,
    "phone": "768-319-1054",
    "address": {
      "street": "8532 Ingalls Circle",
      "city": "Arvada",
      "state": "CO",
      "postalCode": "80003",
      "country": "CA"
    },
    "profileCompletenessScore": 60
  },
  {
    "name": "Eloise Weber",
    "age": 29,
    "phone": "618-357-2104",
    "address": {
      "street": "632 Belmar Drive",
      "city": "Edmond",
      "state": "OK",
      "postalCode": "73025",
      "country": "CA"
    },
    "profileCompletenessScore": 80
  }
])

output:
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId('65e064410dd7e7e802a38940'),
    '1': ObjectId('65e064410dd7e7e802a38941'),
    '2': ObjectId('65e064410dd7e7e802a38942'),
    '3': ObjectId('65e064410dd7e7e802a38943')
  }
}


# Delete one by id
bigboxcode> db.customer.deleteOne({"_id": ObjectId('65e064410dd7e7e802a38940')})

output:
{ acknowledged: true, deletedCount: 1 }


# Try to delete document by wrong _id
bigboxcode> db.customer.deleteOne({"_id": 'nonexistingid'})

output:
{ acknowledged: true, deletedCount: 0 }


# Delete by country
bigboxcode> db.customer.deleteOne({"address.country": "CA"})

output:
{ acknowledged: true, deletedCount: 1 }


# Delete by age
bigboxcode> db.customer.deleteOne({"age": 29})

output:
{ acknowledged: true, deletedCount: 1 }


# Delete by multiple filters
bigboxcode> db.customer.deleteOne({"profileCompletenessScore": {$lte : 50}, "address.country": "US"})

output:
{ acknowledged: true, deletedCount: 1 }

Code Implementations

Here are the usage examples of the MongoDB method in Golang, NodeJS, Java, Python programming languages.

// MongoDB db.collection.deleteOne() method examples in Golang

package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

const uri = "mongodb://bigboxuser:bigboxpass@localhost:27017/?maxPoolSize=20&w=majority"

type Customer struct {
	ID                       int     `bson:"_id,omitempty"`
	Name                     string  `bson:"name"`
	Age                      int     `bson:"age"`
	Phone                    string  `bson:"phone,omitempty"`
	Address                  Address `bson:"address,omitempty"`
	ProfileCompletenessScore int     `bson:"profileCompletenessScore,omitempty"`
}

type Address struct {
	Street     string `bson:"street,omitempty"`
	City       string `bson:"city,omitempty"`
	State      string `bson:"state,omitempty"`
	PostalCode string `bson:"postalCode,omitempty"`
	Country    string `bson:"country,omitempty"`
}

func main() {
	// Initiate mongo client
	mongoClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
	if err != nil {
		fmt.Println("MongoDB connection error: ", err)
		os.Exit(1)
	}
	defer mongoClient.Disconnect(context.Background())

	// Initiate collection instance
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	customerCollection := mongoClient.Database("bigboxcode").Collection("customer")

	// Insert some documents
	customers := []interface{}{
		Customer{
			Name:  "Izabella Conroy",
			Age:   19,
			Phone: "108-679-2154",
			Address: Address{
				Street:     "11 North Vineyard Drive",
				City:       "Minneapolis",
				State:      "Minnesota",
				PostalCode: "19426",
				Country:    "US",
			},
			ProfileCompletenessScore: 30,
		},
		Customer{
			Name:  "Lambert Purdy",
			Age:   28,
			Phone: "(610) 489-3633",
			Address: Address{
				Street:     "305 2nd Ave",
				City:       "Collegeville",
				State:      "Minnesota",
				PostalCode: "81007",
				Country:    "US",
			},
			ProfileCompletenessScore: 40,
		},
		Customer{
			Name:  "Alisa Parker",
			Age:   72,
			Phone: "768-319-1054",
			Address: Address{
				Street:     "8532 Ingalls Circle",
				City:       "Arvada",
				State:      "CO",
				PostalCode: "80003",
				Country:    "CA",
			},
			ProfileCompletenessScore: 60,
		},
		Customer{
			Name:  "Eloise Weber",
			Age:   29,
			Phone: "618-357-2104",
			Address: Address{
				Street:     "632 Belmar Drive",
				City:       "Edmond",
				State:      "OK",
				PostalCode: "73025",
				Country:    "CA",
			},
			ProfileCompletenessScore: 80,
		},
	}

	insertResult, err := customerCollection.InsertMany(ctx, customers)

	if err != nil {
		fmt.Println("Command: db.customer.insertMany(... 4 documents ) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.insertMany(... 4 documents ) | Result: ", insertResult)

	// Delete one by id
	objectId := insertResult.InsertedIDs[0]
	deleteResult, err := customerCollection.DeleteOne(ctx, bson.M{"_id": objectId})
	if err != nil {
		fmt.Println("Command: db.customer.deleteOne(... _id filter ) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.deleteOne(... _id filter) | Result: ", deleteResult)

	// Try to delete document by wrong _id
	deleteResult, err = customerCollection.DeleteOne(ctx, bson.M{"_id": "nonexistingid"})
	if err != nil {
		fmt.Println("Command: db.customer.deleteOne(... _id filter ) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.deleteOne(... _id filter) | Result: ", deleteResult)

	// Delete by country
	deleteResult, err = customerCollection.DeleteOne(ctx, bson.M{"address.country": "CA"})
	if err != nil {
		fmt.Println("Command: db.customer.deleteOne(... country filter ) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.deleteOne(... country filter) | Result: ", deleteResult)

	// Delete by age
	deleteResult, err = customerCollection.DeleteOne(ctx, bson.M{"age": 29})
	if err != nil {
		fmt.Println("Command: db.customer.deleteOne(... age filter ) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.deleteOne(... age filter) | Result: ", deleteResult)

	// Delete by multiple filters
	deleteResult, err = customerCollection.DeleteOne(ctx, bson.M{"profileCompletenessScore": bson.M{"$lte": 50}, "address.country": "US"})
	if err != nil {
		fmt.Println("Command: db.customer.deleteOne(... profile score and country filter ) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.deleteOne(... profile score and country filter) | Result: ", deleteResult)
}

Output:

Command: db.customer.insertMany(... 4 documents ) | Result:  &{[ObjectID("65e071f51982ef168dc8df04") ObjectID("65e071f51982ef168dc8df05") ObjectID("65e071f51982ef168dc8df06") ObjectID("65e071f51982ef168dc8df07")]}

Command: db.customer.deleteOne(... _id filter) | Result:  &{1}

Command: db.customer.deleteOne(... _id filter) | Result:  &{0}

Command: db.customer.deleteOne(... country filter) | Result:  &{1}

Command: db.customer.deleteOne(... age filter) | Result:  &{1}

Command: db.customer.deleteOne(... profile score and country filter) | Result:  &{1}

NOTES

  • Use the “DeleteOne()” method from “mongo-go-driver
  • Signature of the method-
    • func (coll *Collection) DeleteOne(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*DeleteResult, error)
  • Definition of DeleteOptions

    type DeleteOptions struct {
        Collation *Collation
        Comment interface{}
        Hint interface{}
        Let interface{}
    }
  • Definition of DeleteResult

    type DeleteResult struct {
        DeletedCount int64 `bson:"n"` // The number of documents deleted.
    }
// db.collection.deleteOne() method example in NodeJS

import { MongoClient, ObjectId } from "mongodb";

// Define MongoDB connection URI
const uri = "mongodb://bigboxuser:bigboxpass@127.0.0.1:27017";

async function main() {
  const mongo = new MongoClient(uri);
  await mongo.connect();

  try {
    const database = mongo.db("bigboxcode");
    const customerCollection = database.collection("customer");

    // Insert some documents
    const insertResult = await customerCollection.insertMany([
      {
        name: "Izabella Conroy",
        age: 19,
        phone: "108-679-2154",
        address: {
          street: "11 North Vineyard Drive",
          city: "Minneapolis",
          state: "Minnesota",
          postalCode: "19426",
          country: "US",
        },
        profileCompletenessScore: 30,
      },
      {
        name: "Lambert Purdy",
        age: 28,
        phone: "(610) 489-3633",
        address: {
          street: "305 2nd Ave",
          city: "Collegeville",
          state: "Minnesota",
          postalCode: "81007",
          country: "US",
        },
        profileCompletenessScore: 40,
      },
      {
        name: "Alisa Parker",
        age: 72,
        phone: "768-319-1054",
        address: {
          street: "8532 Ingalls Circle",
          city: "Arvada",
          state: "CO",
          postalCode: "80003",
          country: "CA",
        },
        profileCompletenessScore: 60,
      },
      {
        name: "Eloise Weber",
        age: 29,
        phone: "618-357-2104",
        address: {
          street: "632 Belmar Drive",
          city: "Edmond",
          state: "OK",
          postalCode: "73025",
          country: "CA",
        },
        profileCompletenessScore: 80,
      },
    ]);

    console.log(
      "Command: db.customer.insertMany(... 4 documents ) | Result: ",
      insertResult
    );

    // Delete one by id
    const objId = insertResult.insertedIds[0];

    let deleteResult = await customerCollection.deleteOne({ _id: objId });
    console.log(
      "Command: db.customer.deleteOne(... _id filter) | Result: ",
      deleteResult
    );

    // Try to delete document by wrong _id
    deleteResult = await customerCollection.deleteOne({ _id: "nonexistingid" });
    console.log(
      "Command: db.customer.deleteOne(... _id filter) | Result: ",
      deleteResult
    );

    // Delete by country
    deleteResult = await customerCollection.deleteOne({
      "address.country": "CA",
    });
    console.log(
      "Command: db.customer.deleteOne(... country filter) | Result: ",
      deleteResult
    );

    // Delete by age
    deleteResult = await customerCollection.deleteOne({ age: 29 });
    console.log(
      "Command: db.customer.deleteOne(... age filter) | Result: ",
      deleteResult
    );

    // Delete by multiple filters
    deleteResult = await customerCollection.deleteOne({
      profileCompletenessScore: { $lte: 50 },
      "address.country": "US",
    });
    console.log(
      "Command: db.customer.deleteOne(... profile score and country filter) | Result: ",
      deleteResult
    );
  } catch (error) {
    console.error("Error:", error);
  } finally {
    await mongo.close();
    console.log("Closed connection to the server");
  }
}

await main();

process.exit(0);

Output:

Command: db.customer.insertMany(... 4 documents ) | Result:  {
  acknowledged: true,
  insertedCount: 4,
  insertedIds: {
    '0': new ObjectId('65e1f716fda99d90345b0fcb'),
    '1': new ObjectId('65e1f716fda99d90345b0fcc'),
    '2': new ObjectId('65e1f716fda99d90345b0fcd'),
    '3': new ObjectId('65e1f716fda99d90345b0fce')
  }
}

Command: db.customer.deleteOne(... _id filter) | Result:  { acknowledged: true, deletedCount: 1 }

Command: db.customer.deleteOne(... _id filter) | Result:  { acknowledged: true, deletedCount: 0 }

Command: db.customer.deleteOne(... country filter) | Result:  { acknowledged: true, deletedCount: 1 }

Command: db.customer.deleteOne(... age filter) | Result:  { acknowledged: true, deletedCount: 1 }

Command: db.customer.deleteOne(... profile score and country filter) | Result:  { acknowledged: true, deletedCount: 1 }

NOTES

  • Use NodeJS “deleteOne()” method from the package “mongodb“.
  • Method signatures are-
    • deleteOne(filter?: Filter<TSchema>, options?: DeleteOptions): Promise<DeleteResult>
# db.collection.deleteOne() method example in Python

from pymongo import MongoClient, WriteConcern
import re
from datetime import datetime

# Create MongoDB client
mongo_client = MongoClient("mongodb://bigboxuser:bigboxpass@127.0.0.1:27017/")

# Select database and collection
mongo_database = mongo_client.bigboxcode
customer_collection = mongo_database.customer

try:
    insert_result = customer_collection.insert_many(
        [
            {
                "name": "Izabella Conroy",
                "age": 19,
                "phone": "108-679-2154",
                "address": {
                    "street": "11 North Vineyard Drive",
                    "city": "Minneapolis",
                    "state": "Minnesota",
                    "postalCode": "19426",
                    "country": "US",
                },
                "profileCompletenessScore": 30,
            },
            {
                "name": "Lambert Purdy",
                "age": 28,
                "phone": "(610) 489-3633",
                "address": {
                    "street": "305 2nd Ave",
                    "city": "Collegeville",
                    "state": "Minnesota",
                    "postalCode": "81007",
                    "country": "US",
                },
                "profileCompletenessScore": 40,
            },
            {
                "name": "Alisa Parker",
                "age": 72,
                "phone": "768-319-1054",
                "address": {
                    "street": "8532 Ingalls Circle",
                    "city": "Arvada",
                    "state": "CO",
                    "postalCode": "80003",
                    "country": "CA",
                },
                "profileCompletenessScore": 60,
            },
            {
                "name": "Eloise Weber",
                "age": 29,
                "phone": "618-357-2104",
                "address": {
                    "street": "632 Belmar Drive",
                    "city": "Edmond",
                    "state": "OK",
                    "postalCode": "73025",
                    "country": "CA",
                },
                "profileCompletenessScore": 80,
            },
        ]
    )

    print("Command: db.customer.insertMany(... 4 documents ) | Result: ", insert_result)

    # Delete one by id
    obj_id = insert_result.inserted_ids[0]

    delete_result = customer_collection.delete_one({"_id": obj_id})
    print("Command: db.customer.deleteOne(... _id filter) | Result: ", delete_result)

    # Try to delete document by wrong _id
    delete_result = customer_collection.delete_one({"_id": "nonexistingid"})
    print("Command: db.customer.deleteOne(... _id filter) | Result: ", delete_result)

    # Delete by country
    delete_result = customer_collection.delete_one({"address.country": "CA"})
    print(
        "Command: db.customer.deleteOne(... country filter) | Result: ", delete_result
    )

    # Delete by age
    delete_result = customer_collection.delete_one({"age": 29})
    print("Command: db.customer.deleteOne(... age filter) | Result: ", delete_result)

    # Delete by multiple filters
    delete_result = customer_collection.delete_one(
        {"profileCompletenessScore": {"$lte": 50}, "address.country": "US"}
    )
    print(
        "Command: db.customer.deleteOne(... profile score and country filter) | Result: ",
        delete_result,
    )
finally:
    mongo_client.close()

Output:

Command: db.customer.insertMany(... 4 documents ) | Result:  InsertManyResult([ObjectId('65e203962ed596e528f73284'), ObjectId('65e203962ed596e528f73285'), ObjectId('65e203962ed596e528f73286'), ObjectId('65e203962ed596e528f73287')], acknowledged=True)

Command: db.customer.deleteOne(... _id filter) | Result:  DeleteResult({'n': 1, 'ok': 1.0}, acknowledged=True)

Command: db.customer.deleteOne(... _id filter) | Result:  DeleteResult({'n': 0, 'ok': 1.0}, acknowledged=True)

Command: db.customer.deleteOne(... country filter) | Result:  DeleteResult({'n': 1, 'ok': 1.0}, acknowledged=True)

Command: db.customer.deleteOne(... age filter) | Result:  DeleteResult({'n': 1, 'ok': 1.0}, acknowledged=True)

Command: db.customer.deleteOne(... profile score and country filter) | Result:  DeleteResult({'n': 1, 'ok': 1.0}, acknowledged=True)

NOTES

  • Use method “delete_one” from redis-py.
  • Signature of the method is –
    • def delete_one(
              self,
              filter: Mapping[str, Any],
              collation: Optional[_CollationIn] = None,
              hint: Optional[_IndexKeyHint] = None,
              session: Optional[ClientSession] = None,
              let: Optional[Mapping[str, Any]] = None,
              comment: Optional[Any] = None,
          ) -> DeleteResult
// db.collection.deleteOne() method example in Java

import com.mongodb.client.*;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.InsertManyResult;
import org.bson.Document;

import java.util.List;

public class DeleteOne {
    public static void main(String[] args) {
        String uri = "mongodb://bigboxuser:bigboxpass@localhost:27017/";

        try (MongoClient mongoClient = MongoClients.create(uri)) {
            MongoDatabase database = mongoClient.getDatabase("bigboxcode");
            MongoCollection<Document> customerCollection = database.getCollection("customer");

            // Insert some documents
            InsertManyResult insertResult = customerCollection.insertMany(
                    List.of(
                            new Document("name", "Izabella Conroy")
                                    .append("age", 19)
                                    .append("phone", "108-679-2154")
                                    .append("address", new Document("street", "11 North Vineyard Drive")
                                            .append("city", "Minneapolis")
                                            .append("state", "Minnesota")
                                            .append("postalCode", "19426")
                                            .append("country", "US"))
                                    .append("profileCompletenessScore", 30),
                            new Document("name", "Lambert Purdy")
                                    .append("age", 28)
                                    .append("phone", "(610) 489-3633")
                                    .append("address", new Document("street", "305 2nd Ave")
                                            .append("city", "Collegeville")
                                            .append("state", "Minnesota")
                                            .append("postalCode", "81007")
                                            .append("country", "US"))
                                    .append("profileCompletenessScore", 40),
                            new Document("name", "Alisa Parker")
                                    .append("age", 72)
                                    .append("phone", "768-319-1054")
                                    .append("address", new Document("street", "8532 Ingalls Circle")
                                            .append("city", "Arvada")
                                            .append("state", "CO")
                                            .append("postalCode", "80003")
                                            .append("country", "CA"))
                                    .append("profileCompletenessScore", 60),
                            new Document("name", "Eloise Weber")
                                    .append("age", 29)
                                    .append("phone", "618-357-2104")
                                    .append("address", new Document("street", "632 Belmar Drive")
                                            .append("city", "Edmond")
                                            .append("state", "OK")
                                            .append("postalCode", "73025")
                                            .append("country", "CA"))
                                    .append("profileCompletenessScore", 80)
                    )
            );

            System.out.println("Command: db.customer.insertMany(... 4 documents ) | Result: " + insertResult);

            // Delete one by id
            Document findFirstDocument = customerCollection.find().first();

            DeleteResult deleteResult = customerCollection.deleteOne(findFirstDocument);
            System.out.println("Command: db.customer.deleteOne(... _id filter) | Result: " + deleteResult);

            // Try to delete document by wrong _id
            deleteResult = customerCollection.deleteOne(new Document("_id", "nonexistingid"));
            System.out.println("Command: db.customer.deleteOne(... _id filter) | Result: " + deleteResult);

            // Delete by country
            deleteResult = customerCollection.deleteOne(new Document("address.country", "CA"));
            System.out.println("Command: db.customer.deleteOne(... country filter) | Result: " + deleteResult);

            // Delete by age
            deleteResult = customerCollection.deleteOne(new Document("age", 29));
            System.out.println("Command: db.customer.deleteOne(... age filter) | Result: " + deleteResult);

            // Delete by multiple filters
            deleteResult = customerCollection.deleteOne(new Document("profileCompletenessScore", new Document("$lte", 50)).append("address.country", "US"));
            System.out.println("Command: db.customer.deleteOne(... profile score and country filter) | Result: " + deleteResult);

            mongoClient.close();

        }
    }
}

Output:

Command: db.customer.insertMany(... 4 documents ) | Result: AcknowledgedInsertManyResult{insertedIds={0=BsonObjectId{value=65e20cc560f0790b83cba3cd}, 1=BsonObjectId{value=65e20cc560f0790b83cba3ce}, 2=BsonObjectId{value=65e20cc560f0790b83cba3cf}, 3=BsonObjectId{value=65e20cc560f0790b83cba3d0}}}

Command: db.customer.deleteOne(... _id filter) | Result: AcknowledgedDeleteResult{deletedCount=1}

Command: db.customer.deleteOne(... _id filter) | Result: AcknowledgedDeleteResult{deletedCount=0}

Command: db.customer.deleteOne(... country filter) | Result: AcknowledgedDeleteResult{deletedCount=1}

Command: db.customer.deleteOne(... age filter) | Result: AcknowledgedDeleteResult{deletedCount=1}

Command: db.customer.deleteOne(... profile score and country filter) | Result: AcknowledgedDeleteResult{deletedCount=1}

NOTES

  • Use the method “updateMany()” from MongoCollection.
  • Signatures of the method are-
    • DeleteResult deleteOne(Bson filter)
    • DeleteResult deleteOne(Bson filter, DeleteOptions options)
    • DeleteResult deleteOne(ClientSession clientSession, Bson filter)
    • DeleteResult deleteOne(ClientSession clientSession, Bson filter, DeleteOptions options)

Source Code

Use the following links to get the source code used in this article-

Related Methods

CommandDetails
db.collection.deleteMany() Method Details
db.collection.updateOne() Method Details
db.collection.insertMany() Method Details
db.collection.findOne() Method Details

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.