Using the Mongo Shell: Using Documents

In the following subsections we shall discuss adding a document, adding documents in a batch, querying a document, updating a document, and removing a document.

1. Adding a Document

In this section we shall use the db.collection.insert() JavaScript method to add a document to MongoDB from Mongo shell. The insert() helper method has a different syntax for different versions of MongoDB with some new features added to latter versions as listed in Table 2-2.

To add a document, complete the following steps:

  1. Drop the catalog collection if it already exists before adding a new document or array of documents.

>db.catalog.drop()

  1. Create the BSON document construct to add.

>use catalog

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

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

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

  1. Invoke the db.collection.insert() method on the document using the catalog collection.

>db.catalog.insert(doc1)

  1. Subsequently run the db.collection.find() method to find the documents in the catalog collection.

>db.catalog.find()

The single document added gets listed and includes the _id field. The _id field, which was not specified in the document JSON construct, gets added automatically before the document is added to the database.

A WriteResult object returned by the insert() method includes the field nInserted to indicate the number of documents added. With one document added nInserted field value is 1 as shown in Figure 2-23.

Next, we shall add a BSON document in which the _id field is specified in the BSON document construct.

  1. Specify the same document as earlier but with an additional field _id. The value of the _id field must be an ObjectId object.

>doc1 = {“_id”: 0bjectId(“507fl91e8l0c19729de860ea”), “catalogId”

: “catalog!.”, “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 db.collection.insert method.

>db.catalog.insert(docl)

As before, the insert() method returns a WriteResult object with the nInserted field value as 1 indicating that one document has been added as shown in Figure 2-24.

  1. Subsequently run the db.catalog.find() method to find the documents in the database. The document added gets listed and has the _id field as specified in the document added as shown in Figure 2-25.

For any version of MongoDB the _id field value should be unique among the documents in a collection. To demonstrate, add the following document, which has the _id field set to ObjectId (“507fl91e8l0c19729de860ea”).

>doc2 = {“_id”: ObjectId(“507f191e810c19729de860ea”),”catalogId” : 2, “journal” : ‘Oracle

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

>db.catalog.insert(doc2)

Add another document with the _id field set to the same ObjectId value.

>doc3 = {“_id”: ObjectId(“507f191e810c19729de860ea”),”catalogId” : 3};

>db.catalog.insert(doc3)

A duplicate key error gets generated as shown in Figure 2-26.

2. Adding a Batch of Documents

The support for adding an array of documents was added in MongoDB 2.2. In the pre-2.2 version only a single document could be added with a single invocation of the db.collection.insert() method. To add a batch of documents in MongoDB 3.0.5, specify or create JSON for two documents to be added including the _id fields.

>doc1 = {“_id”: ObjectId(“507f191e810c19729de860ea”), “catalogId” : ‘catalog1’,

“journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle Publishing’, “edition” : ‘November

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

>doc2 = {“_id” : ObjectId(“53fb4b08d17e68cd481295d5”), “catalogId” : ‘catalog2’,

“journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle Publishing’, “edition” : ‘November

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

Drop the catalog collection and invoke the db.catalog.insert() method using an array of documents with collection as catalog.

>db.catalog.drop()

>db.catalog.insert([doc1, doc2])

The insert() method returns a BulkWriteResult object, which includes a field nInserted, which signifies the number of documents added. The two documents in the array are added as two distinct documents as indicated by the nInserted field value as 2. Subsequently run the db.collection.find() method to find the documents in the catalog collection.

>db.catalog.find()

The collection method find() lists two distinct documents as shown in Figure 2-27.

MongoDB 2.6 Mongo shell added support for two new options: writeConcern and ordered. Next, we shall demonstrate the use of these options. The writeConcern option document supports the options listed in Table 2-3.

The write concern w may be set to the values listed in Table 2-4.

Next, we shall add a batch of documents using the writeConcern and ordered options. Specify three BSON documents to be added.

docl = {“_id”: ObjectId(“507f191e810c19729de860ea”), “catalogId” : 2, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’,”title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’}

doc2 = {“_id” : ObjectId(“53fb4b08d17e68cd481295d5”), “catalogId” : 1, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’,”title” : ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’}

doc3 = {“_id” : ObjectId(“53fb4b08d17e68cd481295d6”), “catalogId” : 3, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’}

Using the db.collection.insert() method and a writeConcern (with w set to majority and wtimeout set to 5000) and the ordered option set to true add the array of documents. Again, before running the db.catalog.insert() command drop the catalog collection.

>db.catalog.drop()

>db.catalog.insert([doc3, doc1, doc2], { writeConcern: { w: “majority”, wtimeout: 5000 }, ordered:true })

A BulkWriteResult object gets returned with the nInserted value of 3 as shown in Figure 2-28.

Subsequently invoke db.catalog.find() to list the three documents added. The documents are listed in the order specified in the document array added as shown in Figure 2-29.

A nonmajority w value of 1 cannot be used when a host is not a member of a replica set. For example, run the following commands.

>db.catalog.drop()

>db.catalog.insert([doc3, doc1, doc2], { writeConcern: { w: “1”, wtimeout: 5000 },

ordered:true })

As indicated by the error message, w cannot be 1 as shown in Figure 2-30.

3. Saving a Document

The db.collection.save() method is used to save a document, which is different from the db.collection. insert() method as the insert method always adds a new document or throws an error if a document with the same _id field is already in the database. In contrast the db.collection.save() method updates the document if a document with the same _id already exists in the database and adds a new document if a document with the same _id does not already exist. When a document with the same _id already exists in the database the save method completely replaces the document with the new document. The db.collection. save() method was revised in the MongoDB 2.6 version. The following table, Table 2-5, lists the MongoDB 2.4 and MongoDB 2.6 (and later) version of the save() method.

In this section we shall demonstrate the different uses of the save() method. First, we shall update a document using the save() method. Add the following document using the db.collection.insert() method on the catalog collection.

  1. Before adding the document drop the catalog collection and set the current database to catalog.

>db.catalog.drop()

>use catalog

>doc1 = {“_id”: ObjectId(“507fl91e8l0c19729de860ea”), “catalogId”

: “catalog!.”, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle Publishing’,

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

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

>db.catalog.insert(docl)

  1. The db.collection.insert() method adds the document and returns a WriteResult object with nInserted field as 1. Invoke the db.collection.find() method to list the document added.

>db.catalog.find()

  1. Subsequently construct a document with the same _id as the added document but with some of the fields different.

>doc1 = {“_id”: 0bjectId(“507fl91e8l0c19729de860ea”), “catalogId”

: ‘catalog!.’, “journal” : ‘Oracle Magazine’, “publisher” : ‘Oracle Publishing’,

“edition” : ’11-12-2013′,”title” : ‘Engineering as a

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

  1. Invoke the db.collection.save() method to save the document with some of the fields modified. The writeConcern option, if specified, is ignored.

>db.catalog.save(doc1,{ writeConcern: { w: “majority”, wtimeout: 5000 } })

  1. The db.collection.save() method saves the document and returns a WriteResult object with nMatched and nModified field value as 1. Because the same _id field value is used the document gets updated or modified with the new document. Subsequently invoke the db.collection.find() method on the catalog collection to list the document added and subsequently saved.

>db.catalog.find()

The document added with db.collection.insert() and subsequently saved with db.collection. save() gets listed. The edition field and the author field get modified in the saved (updated) document as shown in Figure 2-31.

In the preceding example the document saved with the save() method has all of the same fields as the document added with the insert() method. In the next example we shall add new fields in the document saved with the save method rather than in the document added with the insert() method.

  1. Construct a BSON document with the _id field, the catalogId field, the journal field, the publisher field, and the edition field but without the title and author fields.

doc2 = {“_id”: ObjectId(“507f191e810c19729de860ea”), “catalogId” :

“catalog2”, “journal” : ‘Oracle Magazine’, “publisher” :

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

  1. Add the document with the db.collection.insert() method in the catalog collection. Before running the command, drop the catalog collection.

>db.cataog.drop()

>db.catalog.insert(doc2)

  1. The insert() method returns a WriteResult object with nInserted field value as 1. A subsequent invocation of the db.collection.find() method on the catalog collection lists the document.

>db.catalog.find()

  1. Having added a document, next we shall update the document using the save() method. Construct a document with all of the same fields and field values as the document added with the insert() method including the _id field and additional fields of title and author.

>doc2 = {“_id”: ObjectId(“507f191e810c19729de860ea”),”catalogId” :

‘catalog2’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ’11-12-2013′,”title” :

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

  1. Save the document with the db.collection.save() method in the catalog collection. The catalog collection is not to be dropped before the following command as we are saving (and modifying) the same document as added before.

>db.catalog.save(doc2)

  1. The save() method modifies the document adding the fields title and author. The save() method returns a WriteResult object with the nInserted and nModified field values as 1. Subsequently invoke the db.collection.find() method to list the document.

>db.catalog.find()

The modified document gets listed with the two additional fields as shown in Figure 2-32. The document has been modified.

In all of the preceding examples of save() we specified the _id field in the document added with insert() and subsequently saved with save method. In the next example of using the save() method we shall invoke the save() method with a different _id field value than in the document added with insert() method. Construct a BSON document as before and add the document using the insert() method. Drop the catalog collection before running the example.

  1. A subsequent invocation of the db.collection.find() method lists the document added.

>db.catalog.drop()

>doc2 = {“_id”: ObjectId(“507f191e810c19729de860ea”),

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

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

> db.catalog.insert(doc2)

>db.catalog.find()

  1. Next, construct another document with the same fields and field values except the _id field value being different. Save the document with the save method.

>doc2 = {“_id”: ObjectId(“507f191e810c19729de860eb”),”catalogId”

: ‘catalog2’, “journal” : ‘Oracle Magazine’, “publisher” :

‘Oracle Publishing’, “edition” : ’11-12-2013′,”title” :

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

>db.catalog.save(doc2)

  1. Subsequently invoke the db.collection.find() method on the catalog collection.

db.catalog.find()

Because the document saved with the save() method has a different _id field value, a new document gets added and two documents get listed with find() as shown in Figure 2-33.

The nUpserted in the WriteResult is 1. Upsert is just a term for an insert when no document matches a query document that could possibly match and update a document. Upsert is used in the context of operations that modify or update a document if a matching document is found. The insert() method does not modify or update a document and the term upsert cannot be used in the context of the insert() method. The save() and update() methods do modify or update a document and upsert is used in the context of these methods.

When a new _id field is used in the document added with insert() and subsequently saved with the save() method the process is called upserting the document.

When the _id field is not specified in the document with insert() and subsequently saved with save() an insert is performed instead of an upsert. Next, we shall discuss an example of insert using the save() method.

  1. Construct a document as before but do not include an _id field. Add the document with the insert() method. A subsequent invocation of the find() method lists the document. Drop the catalog collection as before.

>db.catalog.drop()

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

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

>db.catalog.insert(doc2)

>db.catalog.find()

  1. Next, construct another document with the edition field modified and two new fields title and author.

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

“publisher” : ‘Oracle Publishing’, “edition” : ’11-12-2013′,

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

  1. Invoke the save() method on the updated document.

>db.catalog.save(doc2)

  1. A subsequent invocation of the find() method does not list an updated document but lists two documents.

>db.catalog.find()

Because the document added with insert() and the document saved with save() do not include the _id field, a new document gets added and gets listed with find() as shown in Figure 2-34. The WriteResult object returned has an nInserted field with a value as 1, indicating that a document has been added.

4. Updating a Document

In this section we shall update a document. The db.collection.update() JavaScript method is used to update a document. The method has been revised in MongoDB 2.2 and 2.6. The different versions of the method are shown in Table 2-6.

The update() method parameters including the options, which are optional, are discussed in Table 2-7.

Next, we shall update a document. First, we shall add a document using the insert() method and subsequently we shall update the added document using the update method.

  1. In the mongo command shell run the following commands to add a document.

Before running the command, drop the catalog collection.

>db.catalog.drop()

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

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

>db.catalog.insert(doc1)

  1. Subsequently run the following command to find the added document. >db.catalog.find()
  2. To update the document invoke the update() method with a modified value for the edition field and new fields title and author fields. Include the options parameter consisting of the upsert option set to true.

db.catalog.update(

{ catalogId: “catalog1” },

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

“publisher” : ‘Oracle Publishing’, “edition” : ’11-12-2013′,

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

{ upsert: true}

)

  1. Subsequently invoke the find() method again.

>db.catalog.find()

The document gets updated and a WriteResult object is returned. The nMatched field in the WriteResult object has the value 1, nUpserted 0 and nModified 1 as shown in Figure 2-35.

If key:value expressions are used in the update parameter the complete document is replaced with the document in the update parameter. If update operators expressions such as $set are used in the update() method only the specified fields in the update operator expressions are replaced, not the complete document. If the update parameter contains update operators expressions it must not contain field key:value expressions.

5. Updating Multiple Documents

The update() method updates a single document by default. To update multiple documents use the multi parameter. A requirement for the update() method to update multiple documents is to use the update operators expressions. If the update() method specifies only field:value expressions it cannot update multiple documents.

Next, we shall update multiple documents in MongoDB 3.0.5.

  1. First delete any previously added catalog collection by invoking db.catalog. drop(). Add two documents to the catalog collection using the db.collection. insert() method. Subsequently list the documents in the catalog collection using the db.collection.find() method.

> db.catalog.drop()

>use catalog

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

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

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

db.catalog.insert(docl)

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

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

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

>db.catalog.insert(doc2)

>db.catalog.find()

  1. Next, invoke the db.collection.update() method using update operators expressions with $set updating the edition field and $inc updating the catalogId field. In the options parameter specify multi option as true and also specify the writeConcern option. The wtimeout though specified for w:1 is applicable only for w>1 and is ignored for w:1. Subsequently invoke the db.catalog.find() method to list the updated documents.

>db.catalog.update(

{ journal: ‘Oracle Magazine’},

{

$set: { edition: ’11-12-2013′ },

$inc: { catalogId: 2 }

},

{

multi: true,

writeConcern: { w: 1, wtimeout: 5000 }

}

)

>db.catalog.find()

As the output from the update() method indicates, two documents get matched and two documents get updated as shown in Figure 2-36.

6. Finding One Document

The findOne() method may be used to find a single document from a collection. The syntax of the findOne() method is as follows.

db.collection.findOne(query, <projection>)

Both the method parameters are optional. The query parameter specifies the query selection criteria and is of type document. The <projection> parameter specifies the fields to return. The type of the query and <projection> parameters is document. By default all fields are returned. If multiple documents match a selection criteria or if not selection criteria is specified and the collection has multiple documents the first document that is matched is returned.

Next, we shall add two documents and find one document using findOne() method without any args.

  1. Drop the catalog collection and add two documents to the catalog collection using the db.collection.insert() method.

>db.catalog.drop()

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

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

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

>db.catalog.insert(doc1)

>doc2 = {“_id”: ObjectId(“507f191e810c19729de860ea”),”catalogId”

:”catalog2″, “journal” : ‘Oracle Magazine’, “publisher” :

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

>db.catalog.insert(doc2)

  1. Find one document using the findOne() method.

>db.catalog.findOne()

One of the two documents gets returned as shown in Figure 2-37.

7. Finding All Documents

To find all documents the find() method must be used. The find() method has the following syntax.

db.collection.find(query, <projection>)

The query parameter specifies the query selection criteria and the <projection> parameter specifies the fields to return. None of the parameters is required and both are of type document. The find() method actually returns a cursor and if the method is invoked in the MongoDB shell the cursor is automatically iterated to display the first 20 documents. To run the iterator on the remaining document specify it in the shell.

To find all documents in the catalog collection that may have been added previously and not removed, run the find() method.

>db.catalog.find()

All the documents in the catalog collection get returned as shown in Figure 2-38. To distinguish between the single document returned by the findOne() method and all documents returned by find(), the results from both findOne() and find() are listed.

8. Finding Selected Fields

Both the find() and findOne() methods support the <projection> parameter as mentioned before.

The <projection> parameter specifies the fields to return with a document of the following syntax.

{ fieldl: <boolean>, field2: <boolean> … }

To include a field set the boolean to true or 1. To exclude a field set the field to false or 0. For example, add two documents to the catalog collection using the insert() method. But, first drop the catalog collection.

>db.catalog.drop()

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

“edition” : ‘November December 2013’,”title” : ‘Engineering as a Service’,

“author” : ‘David A. Kelly’}

>db.catalog.insert(doc1)

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

“edition” : ‘November December 2013’,”title” : ‘Quintessential and Collaborative’,

“author” : ‘Tom Haunert’}

>db.catalog.insert(doc2)

Subsequently invoke the findOne() method with the query parameter set to an empty document and the <projection> parameter set to include the edition, title, and author fields.

>db.catalog.findOne(

{ },

{ edition: 1, title: 1, author: 1 }

)

A single document gets returned and only the title, author, and edition fields get returned as shown in Figure 2-39. The _id field is always returned and is not required to be specified in the <projection> parameter as one of the fields to return.

The <projection> parameter may specify to either include field/s or exclude field/s, not both. To demonstrate invoke the findOne() method with edition field excluded, and title and author fields included.

>db.catalog.findOne(

{ },

{ edition: 0, title: true, author: 1 }

)

An exception gets generated indicating that including and excluding fields cannot be mixed as shown in Figure 2-40.

To exclude fields all fields in the <projection> argument must be set to be excluded. For example, in the following invocation of findOne() the catalogId field is set using the query comparison operator $gt and the <projection> parameter value is set to exclude the journal and publisher fields.

>db.catalog.findOne(

{ catalogId : {$gt: 1} },

{ journal: 0, publisher: 0}

)

The findOne() method returns only the document with catalogId greater than 1 and excludes the journal and publisher fields as shown in Figure 2-41.

Even the _id field may be excluded in the <projection> argument. For example, exclude the _id, journal and publisher fields.

>db.catalog.findOne(

{ catalogId : {$gt: 1} },

{ _id:0, journal: 0, publisher: 0}

)

The _id field is also excluded in the output as shown in Figure 2-42.

If the _id field value is to be specified in the query arg of the find() or findOne() method, the ObjectId wrapper class must be used. For example, specify the query arg using the comparison query operator $in and the ObjectId to specify the _id field values. The same _id field values were used in adding the documents. The _id field values would be different for different users; use the _id field values for documents added previously. The _id field values may be found using the db.catalog.find() command.

>db.catalog.find(

{

_id: { $in: [ ObjectId(“55ba5ae4403cc01aa5b078e3”),

ObjectId(“55ba5ae5403cc01aa5b078e4”) ] }

}, { edition: 1, title: 1, author: 1 }

)

The find() method returns the two documents with the specified _id field values as shown in Figure 2-43. Only the fields specified in the <projection> arg are returned.

9. Using the Cursor

As mentioned before the db.collection.find() method returns a cursor and when the find() method is invoked in the shell the first 20 documents are iterated over and displayed by default. The cursor supports several methods and a handle to the cursor object may be obtained to invoke the methods. Some of the methods supported by the cursor are discussed in Table 2-8.

Next, we shall demonstrate the use of some of the cursor methods. Remove the catalog collection and add three documents to the catalog collection using the insert() method.

>db.catalog.drop()

>doc1 = {“_id” : ObjectId(“53fb4b08d17e68cd481295d5″),”catalogId” : 1, “journal” :

‘Oracle Magazine’, “publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’, “title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’} db.catalog.insert(doc1)

>doc2 = {“_id” : ObjectId(“53fb4b08d17e68cd481295d6”), “catalogId” : 2, “journal” :

‘Oracle Magazine’, “publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’, “title” : ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’} >db.catalog.insert(doc2)

>doc3 = {“_id” : ObjectId(“53fb4b08d17e68cd481295d7”), “catalogId” : 3, “journal” :

‘Oracle Magazine’, “publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’} >db.catalog.insert(doc3)

Invoke the forEach method on the cursor returned and invoke the printjson function to output the document as JSON.

>db.catalog.find().forEach(printjson)

The three documents get displayed in JSON format as shown in Figure 2-44.

In the previous example we did not create a variable for the cursor but invoked the forEach() method in sequence to the find() method invocation. We may also specify a variable for the cursor as follows.

A variable may be used if the cursor is to be used for some other purpose also.

var cursor= db.catalog.find();

Subsequently the hasNext() and next() methods are invoked in a ternary/conditional operator to find the next document in the cursor.

var document = cursor.hasNext() ? cursor.next() : null;

If a document is returned, print the JSON form of the document.

if (document) {

print (tojson(document));

}

The JSON form of a document gets output as shown in Figure 2-45.

The cursor methods may be invoked in sequence as in the following find() method invocation in which the limit() method is invoked followed by the sort() method. The limit() method limits the documents returned to two and the sort method sorts by catalogld in ascending order.

>db.catalog.find().limit(2).sort({catalogId: 1})

Two documents with catalogId field in ascending order get returned as shown in Figure 2-46.

10. Finding and Modifying a Document

The findAndModify() method may be used to find and modify a single document and has the following syntax.

db.collection.findAndModify({

query: <document>,

sort: <document>,

remove: <boolean>,

update: <document>,

new: <boolean>,

fields: <document>,

upsert: <boolean>

})

The following parameters listed in Table 2-9 are supported by the findAndModify() method. All parameters are optional except that one of update or remove must be specified.

For example, invoke the findAndModify() method as follows:

  • Set the query parameter to find documents with the journal field as Oracle Magazine.
  • Sort by catalogId field in ascending order.
  • Specify the update parameter with update operators $inc to increment the catalogId field by 1 and the $set operator to set a new value for the edition field.
  • The upsert parameter is set to true and so is the new parameter.
  • The fields parameter specifies the fields to return as catalogId, edition, title, and author.

db.catalog.findAndModify({

query: {journal : “Oracle Magazine”},

sort: {catalogId : 1},

update: {$inc: {catalogId: 1},

$set: {edition: ’11-12-2013′}},

upsert :true, new: true,

fields: {catalogId: 1, edition: 1, title: 1, author: 1}

})

Before invoking the preceding method add some documents, which should have the catalogId field value as a number because the $inc operator cannot be applied to a non-number. Because the parameter new is set to true the method returns the modified document as shown in Figure 2-47.

Both upsert and remove parameter values cannot be specified in the method invocation. For example, run the following command.

db.catalog.findAndModify({

query: {journal : “Oracle Magazine”},

sort: {catalogId : 1},

update: {$inc: {catalogId: 1}, $set: {edition: ’11-12-2013′}},

remove: true,

upsert :true,

new: true,

fields: {catalogId: 1, edition: 1, title: 1, author: 1}

})

As indicated by the following exception both upsert and remove parameter values cannot coexist as shown in Figure 2-48.

11. Removing a Document

The db.collection.remove() method is used to remove document/s. The method has the following syntax in MongoDB version prior to 2.6.

db.collection.remove(

<query>,

<justOne>

)

The remove() method has the following syntax in version 2.6 and later.

db.collection.remove(

<query>,

{

justOne: <boolean>,

writeConcern: <document>

}

)

The method parameters are as listed in Table 2-10.

In version 2.6 and later the remove() method returns a WriteResult object. As an example add three documents, one with catalogId 3 and two with catalogId 2

>db.catalog.drop()

>doc1 = {“_id” : ObjectId(“53fb4b08d17e68cd481295d5″),”catalogId” : 2, “journal” :

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

“title” : ‘Engineering as a Service’,”author” : ‘David A. Kelly’} d b.catalog.insert(doc1)

>doc2 = {“_id” : ObjectId(“53fb4b08d17e68cd481295d6”), “catalogId” : 2, “journal” :

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

“title” : ‘Quintessential and Collaborative’,”author” : ‘Tom Haunert’} >db.catalog.insert(doc2)

>doc3 = {“_id” : ObjectId(“53fb4b08d17e68cd481295d7”), “catalogId” : 3, “journal” :

‘Oracle Magazine’, “publisher” : ‘Oracle Publishing’, “edition” : ‘November December 2013’} >db.catalog.insert(doc3)

Subsequently remove the document/s with catalogId as 2 as follows.

>db.catalog.remove({ catalogId: 2 })

As indicated in the output in Figure 2-49 the two documents with catalogId as 2 are removed (nRemoved is 2) and only the document with catalogId as 3 is returned with the find() method invocation subsequent to removing the documents.

In another example, specify the query using the comparison query operator $gt for the catalogId field. Set justOne to true to remove only one document and set the writeConcern to { w: 1, wtimeout: 5000 }. The value of 1 for the w option provides acknowledgment of write on a single MongoDB server. The wtimeout if specified for w:1 is ignored implying that the a timeout does not occur and an acknowledgment from a single server is returned.

>db.catalog.remove(

{ catalogId: { $gt: 1 } },

{justOne:true, writeConcern: { w: 1, wtimeout: 5000 } }

)

The nRemoved field in the WriteResult object returned indicates that one document got removed as shown in Figure 2-50.

To remove all documents in pre-2.6 version the remove() method is invoked as follows without any args.

>db.catalog.remove()

To remove all documents from a MongoDB version 2.6 and later collection an empty document {} must be provided as an argument as follows.

>db.catalog.remove({})

The remove() method returns a WriteResult object with nRemoved as 3 indicating that three documents have been removed as shown in Figure 2-51.

A document cannot be removed from a capped collection, which is a fixed size collection similar to a circular buffer, using the remove() method. To demonstrate, invoke the remove() method on a capped collection; first drop the catalog collection and create a capped collection as discussed earlier in the section “Creating a Collection.”

>db.catalog.drop()

> db.createCollection(“catalog”, {capped: true, autoIndexId: true, size: 64 * 1024, max: 1000} )

>db.catalog.remove({})

An error message gets displayed as shown in Figure 2-52.

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 *