The Collection
object provides the findAndModify()
function, which performs an atomic write on a single document in a collection. This is extremely useful if you need to ensure that no other processes can write to your document at the same time. The following is the syntax for the findAndModify()
method:
findAndModify(query, sort, update, [options], callback)
The query
parameter is a document that is used to identify which document you want to modify. The request matches the properties and values in the query
parameter with the fields and values of the object, and only those that match the query are modified.
The sort
parameter is an array of [field, sort_order]
pairs that specify which fields to sort on when finding the item to modify. The sort_order
value is 1
for ascending or -1
for descending. The update
parameter is an object that specifies the changes to make to the documents that match the query. Table 14.2 lists the operators that can be used.
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 the object that is being modified. If new
is set to true
in options
, the newly modified object is returned. If new
is set to false
, the premodified object is returned. Getting back the premodified object can be useful if you need to verify changes or store the original somewhere else.
Listing 14.4 performs an atomic write on a single object in the MongoDB database. Lines 9–15 implement the findAndModify()
operation. Notice that the sort
value is [['name', 1]]
, which indicates to sort on name
in ascending order. Also notice that w
is 1
to enable the write concern, and new
is set to true
so that the modified object is returned in the callback function and displayed on the console, as shown in Figure 14.4.
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({type:"supernova"}, function(err, items){
06 items.toArray(function(err, itemArr){
07 console.log("Before Modify: ");
08 console.log(itemArr);
09 nebulae.findAndModify({type:"supernova"}, [['name', 1]],
10 {$set: {type:"Super Nova", updated:true}},
11 {w:1, new:true}, function(err, doc){
12 console.log("After Modify: ");
13 console.log(doc);
14 db.close();
15 });
16 });
17 });
18 });
19 });