Using MongoDB with Node.js: Using Documents

In the following subsections we shall add a document, add a batch of documents, query documents, update documents, delete documents, and run bulk operations on documents.

1. Adding a Single Document

In this section we shall add a document to a MongoDB collection.

  1. First, create a collection called catalog in the local database using the Mongo shell.

>db.createCollection(‘catalog’)

The catalog collection gets created as listed with the show collections command in Mongo shell in Figure 5-18.

  1. Create an addDocument.js script in the C:\Program Files\nodejs\scripts directory. The Collection class provides the insertOne(doc, options, callback) method to add a single document.
  2. In the addDocument.js script add require statements for the Db, Server, and Collection classes.

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

The parameters for the insertOne document are discussed in Table 5-13.

  1. Create a Db instance using the class constructor.

var db = new Db(‘local’, new Server(‘localhost’, 27017));

  1. Open the database using the open() method.

db.open(function(error, db) {

//Get collection catalog });

  1. Invoke the collection() method of Db instance to get a catalog collection in the result callback function.

db.collection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

//Add document with insertOne }

});

  1. Create JSON for a document to add.

doc1 = {“catalogId” : ‘catalog1’, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’,

“title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’};

  1. Add the document using the insertOne() method.

collection.insertOne(doc1, function(error, result){

if (error)

console.log(error);

else{

console.log(“Document added: “+result);

}

});

The addDocument.js is listed.

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) {

if (error)

console.log(error);

else{

db.collection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

doc1 = {“catalogId” : ‘catalog1’, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’,

“title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’};

collection.insertOne(doc1, function(error, result){

if (error)

console.log(error);

else{

console.log(“Document added: “+result);

}

});}

});

}});

  1. Run the addDocument.js script with the following command.

>node addDocument.js

A document gets added. The output from the script is shown in Figure 5-19.

  1. Run the following command in mongo shell to list the document added.

>use local >db.catalog.find()

As shown in Figure 5-20 the added document gets listed.

2. Adding Multiple Documents

In this section we add multiple documents to a MongoDB collection.

  1. Drop the catalog collection in the local database and create the catalog collection again as we shall be using the same collection to add multiple documents.

>use local

>db.catalog.drop()

>db.createCollection(‘catalog’)

The Collection class provides the insertMany(docs, options, callback) method to add multiple documents. The method parameters are discussed in Table 5-14.

  1. Create a script addDocuments.js to add documents. Import the Server, Db, and Collection classes.

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

  1. As in the preceding section on adding a single document obtain a Collection instance for the catalog collection. Create JSON for two documents to add.

docl = {“catalogId” : ‘catalog1’, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’,

“title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’};

doc2 = {“catalogId” : ‘catalog2’, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’,

“title” : ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’};

  1. Using the insertMany() instance method from Collection class, add an array of documents.

collection.insertMany([doc1,doc2], function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

The addDocuments.js script is listed.

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) {

if (error)

console.log(error);

else{

db.collection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

doc1 = {“catalogId” : ‘catalog1’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ‘November December

2013′,”title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’};

doc2 = {“catalogId” : ‘catalog2’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ‘November December

2013′,”title” : ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’};

collection.insertMany([doc1,doc2], function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});}

});

}});

  1. Drop and created the catalog collection and run the script with the following commands.

> db.catalog.drop()

>db.createCollection(‘catalog’)

>node addDocuments.js

The output in Figure 5-21 shows that two documents get added.

Run the db.catalog.find() command in Mongo shell to list the documents added as shown in Figure 5-22.

3. Finding a Single Document

The Collection class provides the findOne(query, options, callback) method to find a single document from a collection. The method parameters are discussed in Table 5-15.

Some of the options supported by the findOne() method are discussed in Table 5-16.

  1. Create a script findOneDocument.js and import the required classes as before.
  2.  Create a Db instance and open the database instance
  3. Create a collection and add an array of documents to the collection. Within the method block for the callback function for the createCollection() method invoke the findOne() method. In the selector query specify the journal field set to ‘Oracle Magazine’. In the options argument specify the fields to return as edition, title. and author and set the skip option to 1. In the callback function the second parameter is the cursor to the document returned by the findOne() method. Output the single document to the console.

collection.findOne({journal:’Oracle Magazine’}, {fields:{edition:1,title:1,author:l}, skip:l}, function(error, result) {

if (error) console.log(error.message);

else

console.log(result);

});

The findOneDocument.js script is listed:

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) {

if (error)

console.log(error);

else{

db.createCollection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

doc1 = {“catalogId’[1] : ‘catalog1’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ‘November December

2013′,”title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’};

doc2 = {“catalogId” : ‘catalog2’, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle

Publishing’, “edition” : ‘November December

2013′,”title” : ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’};

collection.insertMany([doc1,doc2], function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

collection.findOne({journal:’Oracle Magazine’}, {fields:{edition:1,title:1,author:1}, skip:1},

function(error, result) {

if (error) console.log(error.message);

else

console.log(result);

});

}

});

}});

  1. Run the script with the command node findOneDocument.js in a command shell. A single document is output to the console as shown in Figure 5-23. Only the specified fields are output as the fields option was set.

4. Finding All Documents

In this section we shall find all documents from a collection.

  1. Drop the catalog collection from the local database as we shall be using the same collection in this section.

>use local

>db.catalog.drop()

While the findOne document returns a single document the find(query) method may be used to return one or more documents based on the selector query. The find() method has only one parameter, query. and returns a Cursor.

  1. Create a script findAllDocuments.js in the C:\Program Files\nodejs\scripts directory to find one or more or all documents. Import the required classes Db, Collection. and Server.
  2. Create and open a database instance and create a collection called catalog using the createCollection() method. Within the createCollection() method block add two documents to the collection using the insertMany() method. Invoke the find() method to find all documents. If a query is not specified all documents are selected by default. The find() method returns a Cursor over the result set. Invoke the toArray(callback) method on the Cursor object returned to return an array of documents. The callback function to the toArray() method has as the second parameter an array of BSON deserialized objects.

collection.find().toArray(function(error, result) {

if (error) console.warn(error.message);

else

console.log(result);

});

The findAllDocuments.js script is listed:

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) {

if (error)

console.log(error);

else{

db.createCollection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

doc1 = {“catalogId’1 : ‘catalog1’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ‘November December

2013′,”title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’};

doc2 = {“catalogId” : ‘catalog2’, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle

Publishing’, “edition” : ‘November December

2013′,”title” : ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’};

collection.insertMany([doc1,doc2], function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

collection.find().toArray(function(error, result) {

if (error) console.warn(error.message);

else

console.log(result);

});

}

});

}});

  1. Run the script with node findAllDocuments.js to find and list all documents as shown in Figure 5-24.

5. Finding a Subset of Documents

In this section we shall find a subset of documents using the find() method already discussed earlier. We shall use the skip, limit. and fields options to skip some documents, limit the number of documents. and return a subset of fields.

  1. Create a script findSubsetDocuments.js. Import the required classes Collection,

Server. and Db.

  1. Create and open a Db instance and create a collection called catalog as in earlier sections. Within the callback function block for the createCollection() method create an array of documents and add the documents to the collection using the insertMany() method.

doc1 = {“catalogId’1 : ‘catalog1’, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’,

“title” : ‘Engineering as a Service’,”author” : ‘David A.

Kelly’};

doc2 = {“catalogId” : ‘catalog2’, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’,”title” :

‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’};

doc3 = {“catalogId” : ‘catalog3’, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’};

doc4 = {“catalogId” : ‘catalog4’, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’};

docArray=[doc1,doc2,doc3,doc4];

collection.insertMany(docArray, function(error, result){ if (error)

console.log(error);

else{

//Find subset of documents }

});

  1. Within the callback function block for the createCollection() method invoke the find() method. The selector query argument is an empty document. Specify the skip option as 1 and the limit option as 2 and specify the fields option to include edition, title. and author. Use the toArray() method to send the query to the server. The second parameter of the callback function to the toArray() method is the document/s returned by the find() method query.

Output the documents to the console.

collection.find({},{skip:1, limit:2,

fields:{edition:1,title:1,author:1}}).toArray(function(error,result) {

if (error) console.log(error);

else

console.log(result);

});

The findSubsetDocuments.js is listed:

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) {

if (error)

console.log(error);

else{

db.createCollection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

doc1 = {“catalogId” : ‘catalog1’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ‘November December

2013′,”title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’};

doc2 = {“catalogId” : ‘catalog2’, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle

Publishing’, “edition” : ‘November December

2013′,”title” : ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’};

doc3 = {“catalogId” : ‘catalog3’, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle

Publishing’, “edition” : ‘November December

2013′};

doc4 = {“catalogId” : ‘catalog4’, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle

Publishing’, “edition” : ‘November December

2013′};

docArray=[doc1,doc2,doc3,doc4];

collection.insertMany(docArray, function(error, result){ if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

collection.find({},{skip:1, limit:2, fields:{edition:1,title:1,author:1}}).

toArray(function(error,result) {

if (error) console.log(error);

else

console.log(result);

});

}

});

}});

  1. Drop the catalog collection from the local database.

>use local

>db.catalog.drop()

Run the script with the following command.

>node findSubsetDocuments.js

Two different documents get returned and output to the console. Only the edition, title. and author fields get returned for the documents if the documents have those fields. One of the documents returned does not have the title and author fields. and only the edition field is returned as shown in Figure 5-25.

6. Using the Cursor

The find() method does not return the documents as such but returns a Cursor over the result set. The Cursor class provides several methods for getting more information about the documents such as iterating over the documents, counting the documents. and finding the next document in the result set. Some of the Cursor class methods are listed in Table 5-17.

  1. Create a script findWithCursor.js script in the C:\Program Files\nodejs\ scripts directory.
  2. Drop the catalog collection from the local database.

>use local >db.catalog.drop()

  1. Import the Collection, Db. and Server classes.
  2. Create and open a Db instance for local database and subsequently create a catalog collection.
  1. Within the callback function block for the createCollection() method block add some documents using the insertMany() method.

docl = {“catalogId” : ‘catalog!.’, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle

Publishing’, “edition” : ‘November December 2013’,”title” :

‘Engineering as a Service’,”author” : ‘David A. Kelly’};

doc2 = {“catalogId” : ‘catalog2’, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle

Publishing’, “edition” : ‘November December 2013’,”title” :

‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’};

docArray=[doc1,doc2];

collection.insertMany(docArray, function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

  1. Invoke the find() method to obtain a Cursor object. var cursor = collection.find();
  2. Invoke the each(callback) method on the Cursor object to iterate over the documents. The second parameter in the callback function is the document being iterated over. Output the document to the console.

var cursor = collection.find();

cursor.each(function(error, result) {

if (error) console.log(error); else

console.log(result);

});

  1. After the each() method has been invoked on the Cursor the Cursor cannot be used to iterate over the result set again. To demonstrate, invoke the forEach() method to iterate over the result set subsequent to invoking the each() method.

cursor.forEach(function(doc) {

console.log(doc);

}, function(error) {

console.log(error);

});

  1. Next, we shall invoke another method on the Cursor to count the number of documents. Invoke the count() method and in the callback function the second parameter is the count of the documents. Output the count of the documents.

cursor.count(function(error, count) {

if (error) console.log(error);

else

console.log(“Document Count “+count);

});

The findWithCursor.js script is listed:

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) {

if (error)

console.log(error);

else{

db.createCollection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

doc1 = {“catalogId” : ‘catalog1’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ‘November December

2013′,”title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’};

doc2 = {“catalogId” : ‘catalog2’, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle

Publishing’, “edition” : ‘November December

2013′,”title” : ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’};

docArray=[doc1,doc2];

collection.insertMany(docArray, function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

var cursor = collection.find();

cursor.each(function(error, result) {

if (error) console.log(error); else

console.log(result);

});

cursor.forEach(function(doc) {

console.log(doc);

}, function(error) {

console.log(error);

});

cursor.count(function(error, count) {

if (error) console.log(error);

else

console.log(“Document Count “+count); });

}

});

}});

  1. Run the findWithCursor.js script with node findWithCursor.js. The output is shown in Figure 5-26.

When the findWithCursor.js script is run the two documents in the collection are returned when the find() method is invoked followed by the each() method. The each() method iterates over the Cursor to output the documents in the result set. When the forEach() method is invoked the cursor has already been exhausted and an error is output. The count() method invocation outputs the document count.

7. Finding and Modifying a Single Document

In this section we shall find and modify a document using the findAndModify(query, sort, doc, options, callback) method in Collection class. In this chapter we discuss both the deprecated method findAndModify() and its alternatives findOneAndUpdate(), findOneAndReplace(). or findOneAndDelete(). The findAndModify() method returns the original document before modification. The method parameters are discussed in Table 5-18.

In addition to the w, wtimeout, and j options the following options listed in Table 5-19 are also supported.

  1. Create a script findAndModify.js in the C:\Program Files\nodejs\scripts directory.
  2. Drop the catalog collection in the local database with db.catalog.drop().
  3. Add some documents to a collection as in earlier sections. Use numerical values for the catalogId and edition fields to demonstrate sorting.

doc1 = {“catalogId” : 1, “journal” : ‘Oracle Magazine’,
“publisher” : ‘Oracle Publishing’, “edition” : ‘11122013’,”title” :
‘Engineering as a Service’,”author” : ‘David A. Kelly’};
doc2 = {“catalogId” : 2, “journal” : ‘Oracle Magazine’,
“publisher” : ‘Oracle Publishing’, “edition” : ‘11122013’,”title” :
‘Quintessential and
Collaborative’,”author” : ‘Tom Haunert’};
collection.insertMany([doc1,doc2], function(error, result){
if (error)
console.log(error);
else{
console.log(“Documents added: “+result);
}
});

  1. Within the callback function to the createCollection() method invoke the findAndModify() method. The query argument is the document {journal:’Oracle Magazine’}. The sort argument is the array [[‘catalogId’, ‘ascending’], [‘edition’, ‘descending’]], which sorts by catalogId in ascending order and edition in descending order. In the update document set the edition and journal fields to new values using {edition:’11-12-2013′, journal:’OracleMagazine’} as argument. In the options argument set the new option to true with {new:true, w:1}. In the callback function, log the updated document to the console.

collection.findAndModify({journal:’Oracle Magazine’},

[[‘catalogId’, ‘ascending’], [‘edition’, ‘descending’]],

{edition:’11-12-2013′, journal:’OracleMagazine’},

{new:true, w:1}, function(error, result) {

if (error) console.log(error);

else

console.log(result);

});

The findAndModify.js script is listed:

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) { if (error)

console.log(error);

else{

db.createCollection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

doc1 = {“catalogId” : 1, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” :

‘11122013’,”title” : ‘Engineering as a Service’,”author” :

‘David A. Kelly’};

doc2 = {“catalogId” : 2, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” :

‘11122013’,”title” : ‘Quintessential and Collaborative’,”author” :

‘Tom Haunert’};

collection.insertMany([doc1,doc2], function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

collection.findAndModify({journal:’Oracle Magazine’},

[[‘catalogId’, ‘ascending’], [‘edition’, ‘descending’]],

{edition:’11-12-2013′, journal:’OracleMagazine’},

{new:true, w:1}, function(error, result) {

if (error) console.log(error);

else

console.log(result);

});

}

});

}});

  1. Run the script with the command node findAndModify.js to find and modify a document and return the modified document as shown in Figure 5-27.

  1. Run the db.catalog.find() method in Mongo shell to list the updated document. Only one document has been updated as shown in Figure 5-28. Because the catalogId field sort order is set to ascending, the first document found catalogId:1 is the document modified.

8. Finding and Removing a Single Document

The findAndRemove(query, sort, options, callback) method in Collection class is used to find and remove a document. In this chapter we have discussed both the deprecated method findAndRemove() and its alternative findOneAndDelete(). The method parameters are as follows in Table 5-20.

  1. Create a script findAndRemove.js in the C:\Program Files\nodejs\scripts directory.
  2. Drop the catalog collection from the local database with db.catalog.drop().
  3. Add two documents to a collection as discussed before. The catalogId field should have a numerical value as we shall be sorting by the catalogId field.

doc1 = {“catalogId” : 1, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : 11122013,”title” :

‘Engineering as a Service’,”author” : ‘David A. Kelly’};

doc2 = {“catalogId” : 2, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : 11122013,”title” : ‘Quintessential and

Collaborative’,”author” : ‘Tom Haunert’}; docArray=[doc1,doc2];

collection.insertMany(docArray, function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

  1. Invoke the findAndRemove() method using the {journal:’Oracle Magazine’} as the query document and [[‘catalogId’, ‘ascending’]] as the sort array. In the callback function the second parameter is the document to be removed. Log the document removed to the console.

collection.findAndRemove({journal:’Oracle Magazine’},

[[‘catalogId’, ‘ascending’]], {w:1}, function(error, result) {

if (error) console.log(error);

else

console.log(result);

});

The findAndRemove.js script is listed:

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) {

if (error)

console.log(error);

else{

db.createCollection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

doc1 = {“catalogId’1 : 1, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : 11122013,”title”

: ‘Engineering as a Service’,”author” : ‘David A. Kelly’};

doc2 = {“catalogId” : 2, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : 11122013,”title”

: ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’};

collection.insertMany([doc1,doc2], function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

collection.findAndRemove({journal:’Oracle Magazine’},

[[‘catalogId’, ‘ascending’]], {w:1}, function(error, result) {

if (error) console.log(error);

else

console.log(result);

});

}

});

}});

  1. Run the findAndRemove.js script with the command node findAndRemove.js.
    The document removed gets logged to the console as shown in Figure 5-29.

9. Replacing a Single Document

The Collection class provides the findOneAndReplace(filter, replacement, options, callback) method to replace a single document. The method parameters are discussed in Table 5-21.

The options supported by the findOneAndReplace() method are discussed in Table 5-22

  1. Drop the catalog collection from the local database with db.catalog.drop().
  2. Create a findOneAndReplaceDocument.js script in the C:\Program Files\ nodejs\scripts directory.
  3. Get and open a Db instance, create a collection. and add documents to the collection.
  4. Using the findOneAndReplace(filter, replacement, options, callback) method. replace one of the documents with journal field as Oracle Magazine. Provide a replacement document with catalogId as catalog3.

collection.findOneAndReplace({journal:’Oracle Magazine’},

{“catalogId” : ‘catalog3’, “journal” : ‘OracleMagazine’, “publisher” :

‘OraclePublishing’, “edition” : ‘11122013’}, function(error, result) {

if (error) console.warn(error.message);

else

console.log(result);

});

The findOneAndReplaceDocument.js script is listed:

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) {

if (error)

console.log(error);

else{

db.createCollection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

doc1 = {“catalogId’1 : ‘catalog1’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ‘November December

2013′,”title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’};

doc2 = {“catalogId” : ‘catalog2’, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle

Publishing’, “edition” : ‘November December

2013′,”title” : ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’};

collection.insertMany([doc1,doc2], function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

collection.findOneAndReplace({journal:’Oracle Magazine’},

{“catalogId” : ‘catalog3’, “journal” : ‘OracleMagazine’, “publisher” :

‘OraclePublishing’, “edition” : ‘11122013’}, function(error, result) {

if (error) console.warn(error.message);

else

console.log(result);

});

}

});

}});

  1. Run the script to replace a single document with node findOneAndReplaceDocument.js. The original document that gets replaced gets returned and output as shown in Figure 5-30.

  1. Run a query in the Mongo shell with db.catalog.find() to list the documents including the replacement document as shown in Figure 5-31.

Another method that could be used to replace a document is the replaceOne(filter, doc, options, callback) method, which is similar to the findOneAndReplace(filter, replacement, options, callback) method except that the replaceOne method provides fewer options (w, wtimeout, j, upsert, and upsert).

10. Updating a Single Document

In this section we shall update a document. The findOneAndUpdate(filter, update, options, callback) method is used to update one or more documents based on a selector query. The method has the parameters shown in Table 5-23.

The options supported by the findOneAndUpdate() method are the same as for the findOneAndReplace() method and discussed in the preceding section in Table 5-21.

  1. Drop the catalog collection in the local database with db.catalog.drop().
  2. Create an updateDocument.js script in the C:\Program Files\nodejs\scripts directory.
  3. Create a collection called catalog as discussed previously.
  4. Add two documents with only some of the fields set as we shall be adding others as an update.

doc1 = {“catalogId’1 : 1, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’};

doc2 = {“catalogId” : 2, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’};

collection.insertMany([doc1,doc2], function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

  1. Using the findOneAndUpdate(filter, update, options, callback) method with filter as all documents with journal field as ‘Java Magazine’ update one of the documents set to {journal:’Java Magazine’} using the $set operator. Set the upsert option to true so that a new document is added if one not found.

collection.findOneAndUpdate({journal:’Java Magazine’}

, {$set: {journal:’Java Magazine’}}

, {returnOriginal: false ,upsert: true

}

, function(error, result) {

if (error) console.log(error);

else

console.log(result);

});

The second argument for the fields and values to be updated may be specified using any of the update operators. When using the update operator $set to modify field values, not all the fields/values need to be specified. Only the fields to be updated need to be specified.

  1. As another example, update the first matching document that has the journal field set to ‘Oracle Magazine’, using the $set operator in the document argument to update the edition, title. and author fields. As the documents added with insertMany do not include the title and author fields these fields are added when the update is made. In the callback function. output the method result.

collection.update({journal:’Oracle Magazine’},

{$set:{edition:’11-12-2013′, title:’Engineering as a Service’, author:’David A. Kelly’}},

{upsert:true, w: 1}, function(err, result){

if (err)

console.log(err);

else

console.log(result);

});

The updateDocument.js script is listed:

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) {

if (error)

console.log(error);

else{

db.createCollection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

doc1 = {“catalogId” : 1, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ‘November December 2013’};

doc2 = {“catalogId” : 2, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ‘November December 2013’};

collection.insertMany([doc1,doc2], function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

collection.findOneAndUpdate({journal:’Java Magazine’}

, {$set: {journal:’Java Magazine’}}

, {returnOriginal: false ,upsert: true

}

, function(error, result) {

if (error) console.log(error);

else

console.log(result);

});

collection.update({journal:’Oracle Magazine’}, {$set:{edition:’11-12-2013′,

title:’Engineering as a Service’, author:’David A.

Kelly’}}, {upsert:true}, function(error, result) {

if (error) console.log(error);

else

console.log(result);

});

}

});

}});

  1. Run the script with the command node updateDocument.js. The output shown in Figure 5-32 indicates that one document gets upserted.

  1. Run the db.catalog.find() method in Mongo shell to list the document in the collection. One of the documents listed is the upserted document as shown in Figure 5-33. Another document has been updated with some fields added.

In the updated document (not the upserted document) only the fields specified in the $set operator are updated and the other fields are the same as before the update. Only the first matching document is updated.

11. Updating Multiple Documents

In this document we shall update multiple documents using the updateMany(filter, update, options, callback) method. The parameters are discussed in Table 5-24.

  1. Create a script updateDocuments.js in the C:\Program Files\nodejs\scripts directory to update multiple documents.
  1. Add an array of documents to the catalog collection in the catalog database as before using the insertMany() method. Add the catalogId, title. and author fields; fields that are unique to all documents, but don’t add the common fields edition, journal. and publisher.

doc1 = {“catalogId” : ‘catalog1’,”title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’};

doc2 = {“catalogId” : ‘catalog2’, “title” : ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’};

collection.insertMany([doc1,doc2], function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

  1. Invoke the updateMany() method using selection filter to select all documents represented with {}. Specify the update using the $set update operator to add the common fields journal, publisher and edition. In the callback function, log the method result to the console.

collection.updateMany({}, {$set:{edition:’November December 2013′, journal:’Oracle Magazine’,

publisher:’Oracle Publishing’}}, {upsert:true}, function(error, result) {

if (error) console.log(error);

else

console.log(result);

});

The updateDocuments.js script is listed:

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) {

if (error)

console.log(error);

else{

db.createCollection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

doc1 = {”catalogId’1 : ‘catalog1’,”title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’};

doc2 = {“catalogId” : ‘catalog2’, “title” : ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’};

collection.insertMany([doc1,doc2], function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

collection.updateMany({}, {$set:{edition:’November December 2013′,

journal:’Oracle Magazine’, publisher:’Oracle Publishing’}},

{upsert:true}, function(error, result) {

if (error) console.log(error);

else

console.log(result);

});

}

});

}});

  1. Before running the script delete the catalog collection from the Mongo shell using the following commands in the Mongo shell.

>use local >db.catalog.drop()

  1. Run the updateDocuments.js script using the command node updateDocuments.js.

Two documents get matched and the two documents get modified as indicated by the nModified field in the result as shown in Figure 5-34.

  1. Run the db.catalog.find() method in Mongo shell to list the updated documents. Both the documents have the edition, publisher, and journal fields added/updated as shown in Figure 5-35.

12. Removing a Single Document

The findOneAndDelete(filter, options, callback) method may be used to remove one or more documents from a collection. The method parameters are discussed in Table 5-25.

The supported options are discussed in Table 5-26

  1. Create a script removeDocument.js in the C:\Program Files\nodejs\scripts directory.
  2. Add an array of documents to a collection using the insertMany() method.
  3. Invoke the findOneAndRemove() method using a selector query to select all documents with journal as Oracle Magazine and output the callback function result to the console.

collection.findOneAndRemove({journal:’Oracle Magazine’}, function(error, result) {

if (error) console.log(error);

else

console.log(result);

});

The removeDocument.js script is listed:

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) {

if (error)

console.log(error);

else{

db.createCollection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

doc1 = {“catalogId” : ‘catalog1’, “journal” : ‘Oracle
Magazine’, “publisher” : ‘Oracle Publishing’, “edition” :

‘November December 2013’,”title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’};

doc2 = {“catalogId” : ‘catalog2’, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’,”title” :

‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’};

collection.insertMany([doc1,doc2], function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

collection.findOneAndDelete({journal:’Oracle Magazine’}, function(error, result) {

if (error) console.log(error);

else

console.log(result);

});

}

});

}});

  1. Drop the catalog collection in local database with db.catalog.drop().

When the removeDocument.js script is run with node removeDocument.js command, two documents get added and one gets removed. The removed document gets output as shown in Figure 5-36.

  1. Run the db.catalog.find() method in Mongo shell to list the documents. As one of the two added documents has been removed, no documents get listed as shown in Figure 5-37.

The deleteOne(filter, options, callback) method is similar to the findOneAndDelete(filter, options, callback) method except that the deleteOne() method supports only the w, wtimeout and j options.

13. Removing Multiple Documents

The deleteMany(filter, options, callback) method may be used to remove one or more documents from a collection. The method parameters are discussed in Table 5-27.

  1. Create a script removeDocuments.js in the C:\Program Files\nodejs\scripts directory.
  2. Add an array of documents to a collection using the insertMany() method.
  3. Invoke the deleteMany() method using a selector query to select all documents with journal as ‘Oracle Magazine’ and output the callback function result to the console.

collection.deleteMany({journal:’Oracle Magazine’},function(error, result) {

if (error) console.log(error);

else

console.log(result);

});

The removeDocuments.js script is listed:

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

var db = new Db(‘local’, new Server(‘localhost’, 27017)); db.open(function(error, db) {

if (error)

console.log(error);

else{

db.createCollection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

doc1 = {“catalogId” : ‘catalog1’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ‘November December

2013′,”title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’};

doc2 = {“catalogId” : ‘catalog2’, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle

Publishing’, “edition” : ‘November December

2013′,”title” : ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’};

collection.insertMany([doc1,doc2], function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

collection.deleteMany({journal:’Oracle Magazine’},function(error, result) {

if (error) console.log(error);

else

console.log(result);

});

}

});

}});

  1. Drop the catalog collection from the local database.

>use local >db.catalog.drop()

When the removeDocuments.js script is run with the command node removeDocuments.js two documents get added and both get removed. The n in the result is 2 indicating that two documents have been removed as shown in Figure 5-38.

  1. Run the db.catalog.find() method in Mongo shell to list the documents. As one of the two added documents has been removed, no documents get listed as shown in Figure 5-39.

14. Performing Bulk Write Operations

The Collection class provides the bulkWrite(operations, options, callback) method to perform bulk write operations. The method parameters are discussed in Table 5-28.

  1. Create a bulkWriteDocuments.js script in the C:\Program Files\nodejs\ scripts directory.
  2. Drop the catalog collection in the local database.

>use local

>db.catalog.drop()

  1. Create the catalog collection in the script and use the bulkWrite(operations, options, callback) method to perform bulk write operations to add some documents, update a single document, update multiple documents, replace a document, and delete a document. Set ordered option to true, which is also the default so that the bulk write operations are performed in the order specified. The order could be significant if a bulk write operation depends on a preceding bulk write operation. For example, documents in a collection cannot be updated before being added.

collection.bulkWrite([

{ insertOne: { document: {“catalogId’1 : ‘catalog1’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition”: ‘November December 2013’,”title” :

‘Engineering as a Service’,”author” : ‘David A. Kelly’} } },

{ insertOne: { document: {“catalogId” : ‘catalog2’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ‘November December 2013’,”title” :

‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’} } },

{ insertOne: { document: {“catalogId” : ‘catalog3’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ‘November December 2013’} } },

{ insertOne: { document: {“catalogId” : ‘catalog4’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ‘November December 2013’} } }

, { updateOne: { filter: {journal:’Oracle Magazine’}, update: {$set: {journal:’OracleMagazine’}}, upsert:true } }

, { updateMany: { filter: {edition:’November December 2013′}, update: {$set: {edition:’11-12-2013′}}, upsert:true } }

, { deleteOne: { filter: {journal:’Oracle Magazine’} } }

, { replaceOne: { filter: {catalogId:’catalog5′}, replacement: {

“catalogId” : ‘catalog5’, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’}, upsert:true}}]

, {ordered:true, w:1}, function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

Similarly a { deleteMany: { filter: {journal:’Oracle Magazine’} } } bulk write operation may be added to delete all documents for a selection query. A deleteMany() has not been included in the sample script to demonstrate the effect of the other bulk write operations because if deleteMany() is included, all or most documents would get deleted. The bulkWriteDocuments.js script is listed:

Server = require(‘mongodb’).Server;

Db = require(‘mongodb’).Db;

Collection = require(‘mongodb’).Collection;

var db = new Db(‘local’, new Server(‘localhost’, 27017));

db.open(function(error, db) {

if (error)

console.log(error);

else{

db.createCollection(‘catalog’, function(error, collection){

if (error)

console.log(error);

else{

collection.bulkWrite([

{ insertOne: { document: {“catalogId’1 : ‘catalog1’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” :

‘November December 2013’,”title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’}

} },

{ insertOne: { document: {“catalogId” : ‘catalog2’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” :

‘November December 2013’,”title” : ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’} } },

{ insertOne: { document: {“catalogId” : ‘catalog3’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” :

‘November December 2013’} } },

{ insertOne: { document: {“catalogId” : ‘catalog4’, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” :

‘November December 2013’} } }

, { updateOne: { filter: {journal:’Oracle Magazine’}, update: {$set: {journal:’OracleMagazine’}}, upsert:true } }

, { updateMany: { filter: {edition:’November December 2013′}, update: {$set: {edition:’11-12-2013′}}, upsert:true } }

, { deleteOne: { filter: {journal:’Oracle Magazine’} } }

, { replaceOne: { filter: {catalogId:’catalog5′}, replacement: {“catalogId” :

‘catalog5’, “journal” : ‘Oracle Magazine’,

“publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’}, upsert:true}}]

, {ordered:true, w:1}, function(error, result){

if (error)

console.log(error);

else{

console.log(“Documents added: “+result);

}

});

}

});

}});

  1. Run the script with the command node bulkWriteDocuments.js. The output is shown in Figure 5-40.

  1. Subsequently run the db.catalog.find() command in Mongo shell to list the documents as shown in Figure 5-41.

As shown in the output only four documents are listed because four were added initially and one was deleted and subsequently a document was upserted. One of the documents has journal set to OracleMagazine because updateOne was used to update the journal field of one document. The catalog5 catalogId document is the document upserted with replaceOne.

Source: Vohra Deepak (2015), Pro MongoDB™ Development, Apress; 1st ed. edition.

Leave a Reply

Your email address will not be published. Required fields are marked *