Navigation

Remove Data with the mongo Shell

Overview

You can use the remove() method to remove documents from a collection. The method takes a conditions document that determines the documents to remove.

To specify a remove condition, use the same structure and syntax as the query conditions. See Find or Query Data with the mongo Shell for an introduction to query conditions.

Prerequisites

The examples in this section use the restaurants collection in the test database. For instructions on populating the collection with the sample dataset, see Import Example Dataset.

In the mongo shell connected to a running mongod instance, switch to the test database.

use test

Procedures

Remove All Documents That Match a Condition

The following operation removes all documents that match the specified condition.

db.restaurants.remove( { "borough": "Manhattan" } )

The remove operation returns a WriteResult object which contains the status of the operation. nRemoved field specifies the number of documents removed.

Use the justOne Option

By default, the remove() method removes all documents that match the remove condition. Use the justOne option to limit the remove operation to only one of the matching documents.

db.restaurants.remove( { "borough": "Queens" }, { justOne: true } )

Successful operation should return the following WriteResult object.

WriteResult({ "nRemoved" : 1 })

nRemoved field specifies the number of documents removed, in this case 1.

Remove All Documents

To remove all documents from a collection, pass an empty conditions document {} to the remove() method.

db.restaurants.remove( { } )

The remove operation returns a WriteResult object which contains the status of the operation. nRemoved field specifies the number of documents removed.

Drop a Collection

The remove all operation only removes the documents from the collection. The collection itself, as well as any indexes for the collection, remain. To remove all documents from a collection, it may be more efficient to drop the entire collection, including the indexes, and then recreate the collection and rebuild the indexes. Use the drop() method to drop a collection, including any indexes.

db.restaurants.drop()

Upon successful drop of the collection, the operation returns true.

true

If the collection to drop does not exist, the operation will return false.

Additional Information

In the MongoDB Manual, see remove() and drop().

In MongoDB, write operations are atomic on the level of a single document. If a single remove operation removes multiple documents from a collection, the operation can interleave with other write operations on that collection. In the MongoDB Manual, see Atomicity.