Overview
You can use the deleteOne method and the deleteMany 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 Java Driver 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. Follow the Connect to MongoDB step to connect to a running MongoDB instance and declare and define the variable db to access the test database. To begin, including the following import statements.
- import org.bson.Document;
Remove All Documents That Match a Condition
The following operation removes all documents that match the specified condition.
- db.getCollection("restaurants").deleteMany(new Document("borough", "Manhattan"));
Remove All Documents
To remove all documents from a collection, pass an empty conditions document {} to the deleteMany method.
- db.getCollection("restaurants").deleteMany(new Document());
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.getCollection("restaurants").drop();
In the Java Driver documentation, see deleteOne, deleteMany 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.
Supplement
* Getting Started - Update Data with Java Driver
* Getting Started - Data Aggregation with Java Driver
沒有留言:
張貼留言