Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

MongoDB Delete Documents

MongoDB Delete Documents

In the previous chapters, we learned how to add data to and update data in MongoDB collections. In this chapter, we will continue to learn about deleting MongoDB collections.

Commonly used document deletion methods include deleteOne(), deleteMany(), and findOneAndDelete().

Use cases:

1、deleteOne()

The deleteOne() method is used to delete a single document that matches the filter.

Syntax:

db.collection.deleteOne(filter, options)

Example

db.

myCollection

.

deleteOne

(

{

name

:

"Alice"

}

)

;

Return result:

{

    "acknowledged": true,

    "deletedCount": 1

}

2、deleteMany()

The deleteMany() method is used to delete all documents that match the filter.

Syntax:



db.collection.deleteMany(filter, options)

Example

db.

myCollection

.

deleteMany

(

{

status

:

"inactive"

}

)

;

Return result:

{

    "acknowledged": true,

    "deletedCount": 1

}

3、findOneAndDelete()

The findOneAndDelete() method is used to find and delete a single document, and can optionally return the deleted document.

Syntax:

db.collection.findOneAndDelete(filter, options)

Example

db.

myCollection

.

findOneAndDelete

(

   

{

name

:

"Charlie"

}

,

   

{

projection

:

{

name

:

1

,

age

:

1

}

}

)

;

findOneAndDelete returns the deleted document; if no matching document is found, it returns null.

Options for delete operations

The options parameter of these delete methods can usually include the following options:

Example

Delete a single document:



db.myCollection.deleteOne({ name: "Alice" });

Delete multiple documents:



db.myCollection.deleteMany({ status: "inactive" });

Find and delete a single document:



db.myCollection.findOneAndDelete(

    { name: "Charlie" },

    { projection: { name: 1, age: 1 } }

);