MongoDB findOneAndDelete() Function: Introduction, Syntax and Examples

In MongoDB, we store a large number of documents that need to be deleted occasionally. To delete all documents based on a particular query, we have a function findManyAndDelete() which is used if you want to delete multiple documents or delete documents in bulk.

Suppose, you want to delete a single document inside a collection, now it may be possible that the query you passed will match multiple documents as there may be millions of documents, so the result will be in huge data loss. In order to avoid this, you can use the findOneAndDelete() function. This function deletes only a single document and provides a secure, fast, and reliable way to delete data in MongoDB.

In this article, we will take an in-depth look at this method with its syntax, and examples, and we will also use the sort method to further define the criteria before deleting. So let’s start.

MongoDB findOneAndDelete() Function

The findOneAndDelete function deletes a single document from a collection based on the selection criteria. The first document returned matching the filter query expression is removed from the collection. Among the five parameters it can take, the first is the selection criteria which is required, while the others are optional. After a document is deleted successfully, this function returns that deleted document.

Syntax:

db.collection.findOneAndDelete(filter, options)

Here:

  • db is a database object,
  • collection is the name of a collection in which you are finding the document for deleting,
  • filter is a query object that has the condition to find the document which you want to delete,
  • options is an optional argument helpful in performing additional operations. The optional argument can be writeConcern, projection(array projection or aggregation expression), sort, maxTimeMS or collation.

Return:

This function returns the deleted document, if no document is found based on the filter parameter, the return value will be null.

Error:

This function throws an error if the document is not found, there is a connection issue, permission error, or syntax error.

Examples of findOneAndDelete() Function in MongoDB

Let us now look at some examples to demonstrate the findOneAndDelete() function. In the first example, we will use this function directly, while in the second we will perform more precise operations by specifying the sorting criteria.

Deleting a Document using the findOneAndDelete() Function

In this example, we will find and delete the first document that matches the given criteria.

  • Run the MongoDB server
  • Choose the database you want to work with and navigate into it:
show dbs
use dronesGala
  • Before we start, let us give a glance at all the available documents in our collection:
> db.drones.find({}).pretty()

{
        "_id" : ObjectId("615f1672a7c6532312e3a41d"),
        "utility" : [
                "Delivery",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Aurelize Frinworks Hawk 7",
        "price" : 12000,
        "weight" : "34 kilograms",
        "additionalDetails" : {
                "material" : "aluminum",
                "moreUses" : [
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("615f16eca7c6532312e3a41e"),
        "utility" : [
                "Delivery",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Poka Moonskull 2X67",
        "price" : 76400,
        "weight" : "48 kilograms",
        "additionalDetails" : {
                "material" : "nylon",
                "moreUses" : [
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("615f17a5a7c6532312e3a41f"),
        "utility" : [
                "Monitoring or Inspection",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Jade Balestrom RW",
        "price" : 24500,
        "weight" : "27 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Water Inspection"
                ]
        }
}
{
        "_id" : ObjectId("615f1879a7c6532312e3a420"),
        "utility" : [
                "Monitoring or Inspection",
                "Videography",
                "Combat",
                "Rescue"
        ],
        "onSale" : false,
        "name" : "VarX Lourra VQ (Limited Edition)",
        "price" : 49500,
        "weight" : "19 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Security"
                ]
        }
}
{
        "_id" : ObjectId("615f1922a7c6532312e3a421"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Mellori Styxe 175",
        "price" : 15000,
        "weight" : "10 kilograms",
        "additionalDetails" : {
                "material" : "carbon fiber",
                "moreUses" : [
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("6160a831821fd04db70117a7"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Wenderman’s X-copter B32",
        "price" : 19500,
        "weight" : "13 kilograms",
        "additionalDetails" : {
                "material" : "carbon fiber",
                "moreUses" : [
                        "Monitoring or Inspection",
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("6160a85a821fd04db70117a8"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "GarX Jerrom BQ (Limited Edition)",
        "price" : 39500,
        "weight" : "19 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Photography",
                        "Security"
                ]
        }
}
  • Finding and deleting a document with specific criteria using the findOneAndDelete() function:
> db.drones.findOneAndDelete({name:"Poka Moonskull 2X67"})

{
        "_id" : ObjectId("615f16eca7c6532312e3a41e"),
        "utility" : [
                "Delivery",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Poka Moonskull 2X67",
        "price" : 76400,
        "weight" : "48 kilograms",
        "additionalDetails" : {
                "material" : "nylon",
                "moreUses" : [
                        "Recreation"
                ]
        }
}
  • Let us take a look at our collection again after the operation:
> db.drones.find({}).pretty()
{
        "_id" : ObjectId("615f1672a7c6532312e3a41d"),
        "utility" : [
                "Delivery",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Aurelize Frinworks Hawk 7",
        "price" : 12000,
        "weight" : "34 kilograms",
        "additionalDetails" : {
                "material" : "aluminum",
                "moreUses" : [
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("615f17a5a7c6532312e3a41f"),
        "utility" : [
                "Monitoring or Inspection",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Jade Balestrom RW",
        "price" : 24500,
        "weight" : "27 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Water Inspection"
                ]
        }
}
{
        "_id" : ObjectId("615f1879a7c6532312e3a420"),
        "utility" : [
                "Monitoring or Inspection",
                "Videography",
                "Combat",
                "Rescue"
        ],
        "onSale" : false,
        "name" : "VarX Lourra VQ (Limited Edition)",
        "price" : 49500,
        "weight" : "19 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Security"
                ]
        }
}
{
        "_id" : ObjectId("615f1922a7c6532312e3a421"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Mellori Styxe 175",
        "price" : 15000,
        "weight" : "10 kilograms",
        "additionalDetails" : {
                "material" : "carbon fiber",
                "moreUses" : [
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("6160a831821fd04db70117a7"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Wenderman’s X-copter B32",
        "price" : 19500,
        "weight" : "13 kilograms",
        "additionalDetails" : {
                "material" : "carbon fiber",
                "moreUses" : [
                        "Monitoring or Inspection",
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("6160a85a821fd04db70117a8"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "GarX Jerrom BQ (Limited Edition)",
        "price" : 39500,
        "weight" : "19 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Photography",
                        "Security"
                ]
        }
}

We can see that the first document that matched the specified criteria, has been deleted with the findOneAndDelete() function.

Deleting a Document with a Sort Criteria Using findOneAndDelete() Function

In this example, we will delete the first document that matches the specified sort criteria.

Here we are sorting the document based on the price in descending order, if you want to sort in ascending you can use 1 instead of -1.

> db.drones.findOneAndDelete( { price: 39500 }, { sort: { price: -1 } } )

{
        "_id" : ObjectId("6160a85a821fd04db70117a8"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "GarX Jerrom BQ (Limited Edition)",
        "price" : 39500,
        "weight" : "19 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Photography",
                        "Security"
                ]
        }
}
  • Checking all our documents after the operation:
> db.drones.find({}).pretty()
{
        "_id" : ObjectId("615f1672a7c6532312e3a41d"),
        "utility" : [
                "Delivery",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Aurelize Frinworks Hawk 7",
        "price" : 12000,
        "weight" : "34 kilograms",
        "additionalDetails" : {
                "material" : "aluminum",
                "moreUses" : [
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("615f17a5a7c6532312e3a41f"),
        "utility" : [
                "Monitoring or Inspection",
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Jade Balestrom RW",
        "price" : 24500,
        "weight" : "27 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Water Inspection"
                ]
        }
}
{
        "_id" : ObjectId("615f1879a7c6532312e3a420"),
        "utility" : [
                "Monitoring or Inspection",
                "Videography",
                "Combat",
                "Rescue"
        ],
        "onSale" : false,
        "name" : "VarX Lourra VQ (Limited Edition)",
        "price" : 49500,
        "weight" : "19 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Security"
                ]
        }
}
{
        "_id" : ObjectId("615f1922a7c6532312e3a421"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Mellori Styxe 175",
        "price" : 15000,
        "weight" : "10 kilograms",
        "additionalDetails" : {
                "material" : "carbon fiber",
                "moreUses" : [
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("6160a831821fd04db70117a7"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Wenderman’s X-copter B32",
        "price" : 19500,
        "weight" : "13 kilograms",
        "additionalDetails" : {
                "material" : "carbon fiber",
                "moreUses" : [
                        "Monitoring or Inspection",
                        "Recreation"
                ]
        }
}

The findOneAndDelete() function has successfully deleted the first document that matched the specified descending sort criteria.

Conclusion

MongoDB is considered the best NoSQL database. It allows users to specify their own schema. You can use the MongoDB driver to interact with it locally on your system. Unlike any other database, in MongoDB you do not need to provide an ID or index manually, it will automatically generate a unique ID for each document when inserted. In this article, we have seen how easy it is to remove a single document from a large set of documents in MongoDB while performing other operations like sorting. Hope you enjoy reading the content!

Read More: 

Reference

db.collection.findOneAndDelete() — MongoDB Manual

Aneesha S
Aneesha S
Articles: 172