At times you may need to delete documents from your MongoDB collection to control space consumption, improve performance, and keep things clean. The remove()
method on Collection
objects makes it very simple to delete documents from a collection. The syntax for the remove()
method is shown below:
remove([query], [options], [callback])
The query
parameter is a document that is used to identify which document(s) you want to delete. The request matches the properties and values in query
with the fields and values of the object, and only those that match the query are updated. If no query
is provided, then all the documents in the collection are deleted.
The options
parameter specifies the database change options described in Table 14.1. The callback
parameter is required if you are implementing a write concern in options
. The first parameter of callback
is an error, and the second parameter is a count of the documents that were deleted.
Listing 14.7 uses the remove()
method to delete objects from a collection. In lines 9–18, remove()
and callback
query the collection for documents whose type
is planetary
and deletes them from the collection. Notice that the results
parameter of callback
is the count of documents deleted. Figure 14.7 shows the output of Listing 14.7.
Note
To run the code in this exercise, please run the code in exercise 14.1 first to reset the data that may have changed by running other exercises in this chapter.
01 var MongoClient = require('mongodb').MongoClient;
02 MongoClient.connect("mongodb://localhost/", function(err, db) {
03 var myDB = db.db("astro");
04 myDB.collection("nebulae", function(err, nebulae){
05 nebulae.find(function(err, items){
06 items.toArray(function(err, itemArr){
07 console.log("Before Delete: ");
08 console.log(itemArr);
09 nebulae.remove({type:"planetary"}, function(err, results){
10 console.log("Deleted " + results + " documents.");
11 nebulae.find(function(err, items){
12 items.toArray(function(err, itemArr){
13 console.log("After Delete: ");
14 console.log(itemArr);
15 db.close();
16 });
17 });
18 });
19 });
20 });
21 });
22 });