Using Spring Data MongoDB with Template

In this section we shall use a MongoDB template to perform CRUD operations on MongoDB server. The term “template” refers to an implementation of MongoDB operations such as create, find, update, delete, aggregate, upsert, and count. The common CRUD operations on a MongoDB datastore may be performed using the org.springframework.data.mongodb.core.MongoOperations interface.

  1. Create a Java class com.mongo.core.App to run CRUD operations on MongoDB server.
  2. The org.springframework.data.mongodb.core.MongoTemplate class implements the MongoOperations interface. A MongoTemplate instance may be obtained using the ApplicationContext. Create an ApplicationContext as follows.

ApplicationContext context = new AnnotationConfigApplicationContext( SpringMongoApplicationConfig.class);

The getBean(String name,Class requiredType) method returns a named bean of the specified type. The bean name for a MongoTemplate is mongoTemplate. The class type is MongoOperations.class.

MongoOperations ops = context.getBean(“mongoTemplate”, MongoOperations.class);

  1. The MongoOperations instance may be used to perform various CRUD operations on a domain object stored in the MongoDB. Add the static methods listed in Table 10-3 to the App.java class and add method invocations for the methods in the main method. The App class method names are same or similar to the MongoOperations method names.
  2. Add class variables for a MongoOperations instance ops and two Catalog instances catalog1 and catalog2.

static MongoOperations ops;

static Catalog catalog1;

static Catalog catalog2;

In the following subsections we shall invoke the methods listed in Table 10-3 to create a collection, create document instances, and run CRUD operations.

1. Creating a MongoDB Collection

First, we need to create a collection to which to add documents. The MongoOperations interface provides the overloaded method createCollection() to create a collection. Each of the createCollection() methods returns a com.mongodb.DBCollection instance as discussed in Table 10-4.

We shall create a collection in the createCollection() class method in the App application. First, find if a collection by the name catalog, which we want to create, already exists. The MongoOoperations interface provides the collectionExists(String collectionName) and collectionExists(Class<T> entityClass) methods to find if a collection exists.

  1. In an if-else statement find if the catalog collection exists. If the collection does not exist create the collection using the createCollection(String collectionName) method. If the collection does exist drop the collection using the dropCollection(String collectionName) method and create the collection again using the createCollection(String collectionName) method. The createCollection() class method is listed:

private static void createCollection() {

if (!ops.collectionExists(“catalog”)) {

ops.createCollection(“catalog”);

} else {

ops.dropCollection(“catalog”);

ops.createCollection(“catalog”);

}

}

  1. Invoke the createCollection() method in the main method.
  2. Run the App.java application to create a collection called catalog in the local database. To run App.java right-click on App.java in Package Explorer and select Run As ➤ Java Application as shown in Figure 10-6.

  1. Run the command show collections to list the collections after running the App.java application to create a collection. The catalog collection gets listed as shown in Figure 10-7.

2. Creating Document Instances

We shall be performing CRUD operations on MongoDB documents, and we have added class variables for the document instances so that we may use the same document instance for the different method invocations and do not have to create a new document instance in each method. In the createCatalogInstances() method, create two instances of Catalog using the class constructor. One or more of the field values may be kept empty as the only required field is _id, which is generated automatically.

catalogl = new Catalog(“catalog1”, “Oracle Magazine”, “Oracle Publishing”,

“November-December 2013”, “Engineering as a Service”,

“David A. Kelly”);

catalog2 = new Catalog(“catalog2”, “Oracle Magazine”, “Oracle Publishing”,
“November-December 2013”, “Quintessential and Collaborative”,”Tom Haunert”);

3. Adding a Document

The MongoOperations interface provides the overloaded save() methods and the overloaded insert() methods to add documents. The insert() method is used to initially store a document in the database while the save() method is used to add a new document if a document with the same _id does not exist and update the document if the document with the same _id already exists. If it is not known if a document with a particular _id could already be in the database, use the save() method because the insert() method would fail if a document with the same _id already exists. We shall use the save() method in this section. In the next subsection we shall also discuss the insert() method to add a collection of documents.

The save() method updates the document if a document with the same _id is already in the database. If a document with the same _id does not exist a new document is added, and an upsert is performed.

The _id is generated automatically. If the entity type of the object to save has an Id property, a property annotated with @Id, it is set with the generated _id value from MongoDB. If the Id property is of type String its value is set using an ObjectId instance created from the _id field value. The two overloaded save() methods are discussed in Table 10-5.

  1. In the addDocument() method create an instance of Catalog.

catalog1 = new Catalog(“catalog1”, “Oracle Magazine”, “Oracle Publishing”, “November-December 2013”, “Engineering as a Service”, “David A. Kelly”);

  1. Invoke the save(Object objectToSave, String collectionName) method using the Catalog instance as the first argument and collection name catalog as the second argument. A collection is created implicitly if not already in the database. For example, the catalog collection does not have to be in the MongoDB database before invoking the save() method with collection name catalog.

ops.save(catalog1, “catalog”);

If the save(Object objectToSave) method is used to save to a particular collection and the collection does not already exist, a collection with the same name as the object class is created implicitly.

ops.save(catalogl);

  1. Output the automatically generated _id that is set in the Id property. System.out.println(“MongoDB generated Id: ” + catalog1.getId());
  2. Similarly add another document.

catalog2 = new Catalog(“catalog2”, “Oracle Magazine”,”Oracle Publishing”, “November-December 2013″,”Quintessential and Collaborative”, “Tom Haunert”); ops.save(catalog2, “catalog”);

System.out.println(“MongoDB generated Id: ” + catalog2.getId());

The addDocument() method is as follows.

private static void addDocument() {

catalog1 = new Catalog(“catalog1”, “Oracle Magazine”,

“Oracle Publishing”, “November-December 2013”,

“Engineering as a Service”, “David A. Kelly”); ops.save(catalog1, “catalog”);

//ops.save(catalog1);

System.out.println(“MongoDB generated Id: ” + catalog1.getId());

catalog2 = new Catalog(“catalog2”, “Oracle Magazine”,

“Oracle Publishing”, “November-December 2013”,

“Quintessential and Collaborative”, “Tom Haunert”);

ops.save(catalog2, “catalog”);

System.out.println(“MongoDB generated Id: ” + catalog2.getId());

}

When the App.java application is run with method invocation of the addDocument() method, two documents get added to the catalog collection. The automatically generated _id field values get output the Eclipse Console as shown in Figure 10-8.

  1. To list the two documents added, run the db.catalog.find() method in Mongo shell as shown in Figure 10-9.

The MongoOperations interface also provides the overloaded insert() method to add a single document as discussed in Table 10-6.

4. Adding a Document Batch

In this section we shall add a batch of documents instead of a single document. The MongoOperations interface provides the overloaded insert() methods and insertAll() method to add or insert a batch of objects to a collection as discussed in Table 10-7. We shall demonstrate each of the three methods in Table 10-7 to add a list of documents to a collection.

  1. Add a batch of documents using the addDocumentBatch() custom method in the App application.
  2. Create an ArrayList of Catalog instances. Create new Catalog instances catalogl and catalog2. The Catalog instances catalog1 and catalog2 could be the same as those created in the addDocument() custom method. As catalog1 and catalog2 are class variables, the same instances may be reused.

catalog1 = new Catalog(“catalog1”, “Oracle Magazine”,

“Oracle Publishing”, “November-December 2013”,

“Engineering as a Service”, “David A. Kelly”); catalog2 = new Catalog(“catalog2”, “Oracle Magazine”,

“Oracle Publishing”, “November-December 2013”,

“Quintessential and Collaborative”, “Tom Haunert”);

ArrayList arrayList = new ArrayList();

arrayList.add(catalog1);

arrayList.add(catalog2);

  1. Next, use one of the following methods to add a batch of documents:
    • Add the ArrayList instance using the insert(Collection<? extends Object> batchToSave, String collectionName) method to the catalog collection.

ops.insert(arrayList, “catalog”);

    • Alternatively add the batch of objects using the insert(Collection<? extends Object> batchToSave, Class<?> entityClass) method.

ops.insert(arrayList,Catalog.class);

    • Or theinsertAll(Collection<? extends Object> objectsToSave) method may be used to add the ArrayList. The database collection name to use is determined based on the class.

ops.insertAll(arrayList);

For all of the insert() methods and the insertAll() method the collection is created implicitly if not already created.

Note The source code includes implementations for each of the two overloaded insert() methods and for the insertAll() method to add a batch of documents. only one of the method implementations should be invoked at a time to add a batch of two documents. the other method invocations may be commented out.

  1. Remove the catalog collection before adding a batch of documents with the following commands in Mongo shell.

>use local >db.catalog.drop()

When the App application is run to invoke the addDocumentBatch() method a batch of documents gets added to the catalog collection.

  1. Subsequently run the db.catalog.find() method in Mongo shell to list the documents added as shown in Figure 10-10. The _id is generated automatically.

5. Finding a Document by Id

In this section we shall find a document by Id. The MongoCollection interface provides the overloaded findById() methods discussed in Table 10-8 for finding a document by Id.

In this section we shall find a document by Id using the findById(Object id, Class<T> entityClass, String collectionName) method.

  1. In the findById() method in the App application create a Catalog instance catalog1.

catalog1 = new Catalog(“catalog1”, “Oracle Magazine”,

“Oracle Publishing”, “November-December 2013”,

“Engineering as a Service”, “David A. Kelly”);

  1. Save the catalog1 instance to the catalog collection using the save() method. ops.save(catalog1, “catalog”);
  2. Find the document using the findById() method using the catalog1.getId() method invocation for the id argument, Catalog.class for the entity class argument, and catalog as the collection name.

Catalog catalog = ops.findById(catalog1.getId(),Catalog.class,”catalog”);

Alternatively, use the other findById() method.

Catalog catalog = ops.findById(catalog1.getId(), Catalog.class);

  1. Subsequently, output the field values from the Catalog instance found by id.

System.out.println(“Id in Catalog instance: ” + catalog1.getId());
System.out.println(“Journal : ” + catalog.getJournal());
System.out.println(“Publisher : ” + catalog.getPublisher());
System.out.println(“Edition : ” + catalog.getEdition());
System.out.println(“Title : ” + catalog.getTitle());
System.out.println(“Author : ” + catalog.getAuthor());

The findById() method in the App application is as follows.

private static void findById() {

catalogl = new Catalog(“catalog1”, “Oracle Magazine”,

“Oracle Publishing”, “November-December 2013”,

“Engineering as a Service”, “David A. Kelly”);

ops.save(catalog1);

// Catalog catalog = ops.findById(catalog1.getId(),

// Catalog.class,”catalog”);

Catalog catalog = ops.findById(catalog1.getId(), Catalog.class);

System.out.println(“Id in Catalog instance: ” + catalog1.getId());

System.out.println(“Journal   :  ”  + catalog.getJournal());

System.out.println(“Publisher : ” + catalog.getPublisher());
System.out.println(“Edition : ” + catalog.getEdition());
System.out.println(“Title : ” + catalog.getTitle());
System.out.println(“Author : ” + catalog.getAuthor());

}

  1. Run the App.java. The output lists the field values from the document found by Id as shown in Figure 10-11. What is to be noted is that the id for the Catalog instance catalog1 is not the id value (catalog1) specified in the constructor, but the automatically generated id value.

6, Finding One Document

Another method used to find a single document is the overloaded findOne(), which has the following variants, discussed in Table 10-9.

In this section we shall find a single document of type Catalog using a Query object from the catalog collection in the findOne() method in the App application. First, we need to construct the Query object to find the single document. The BasicOuery class extends Query and provides the following constructors, discussed in Table 10-10.

  1. Drop any previously created collection called catalog using the following JavaScript method in Mongo shell.

>db.catalog.drop()

  1. In the findOne() method in App application invoke the createCatalogInstances() method to create Catalog instances and save the entity instances using the save() method.

createCatalogInstances();

ops.save(catalog1);

ops.save(catalog2);

  1. Create a BasicDBObject instance using the BasicDBObject(String key, Object value) constructor. Specify key as id and value as the ObjectId instance created from the id in the catalog1 instance obtained using the getId() method.

DBObject dbObject = new BasicDBObject(“id”, new ObjectId(catalog1.getId()));

  1. Using the BasicDBobject instance create a BasicOuery object.

BasicOuery query = new BasicOuery(dbObject);

  1. Using the BasicQuery object find a single document from the catalog collection of entity class type Catalog using either of the findOne() methods.

private static void findOne() {

createCatalogInstances();
ops.save(catalog1);
ops.save(catalog2);
DBObject dbObject = new BasicDBObject(“id”, new ObjectId(
catalog1.getId()));
BasicQuery query = new BasicQuery(dbObject);
Catalog catalog = ops.findOne(query, Catalog.class);
// Catalog catalog = ops.findOne(query, Catalog.class,”catalog”);
System.out.println(“Id in Catalog instance: ” + catalog1.getId());
System.out.println(“Journal : ” + catalog.getJournal());
System.out.println(“Publisher : ” + catalog.getPublisher());
System.out.println(“Edition : ” + catalog.getEdition());
System.out.println(“Title : ” + catalog.getTitle());
System.out.println(“Author : ” + catalog.getAuthor());

Catalog catalog = ops.findOne(query, Catalog.class);

// Catalog catalog = ops.findOne(query, Catalog.class/’catalog’1);

  1. Run the App application to save some Catalog instances and find one of the

Catalog instances using the findOne() method in MongoOperations. The output from the findOne() method is shown in the Eclipse Console in Figure 10-12.

A new Query instance to be given to the findOne() method may also be created using a criteria definition with the Query(CriteriaDefinition criteriaDefinition) constructor. The Criteria class implements the CriteriaDefinition interface and provides several methods to create a criterion and return a Criteria instance. Use the where(String key) method to specify a key for a criterion and subsequently invoke the is(Object o) method to compare the key to the id field value in the catalog2 Catalog instance.

  1. Using the Criteria instance returned by the sequence method invocation of where() and is() methods creates a Query instance and using the Query instance invokes the findOne(Query query, Class<T> entityClass) method.

String _id = catalog2.getId();

Catalog catalog = ops.findOne(new Query(Criteria.where(“_id”).is(_id)), Catalog.class);

  1. Output the field values in the Catalog instance returned by the findOne() method.

System.out.println(“Id in Catalog instance: ” + catalog2.getId());

System.out.println(“Journal : ” + catalog.getJournal());

System.out.println(“Publisher : ” + catalog.getPublisher());

System.out.println(“Edition : ” + catalog.getEdition());

System.out.println(“Title : ” + catalog.getTitle());

System.out.println(“Author : ” + catalog.getAuthor());

When the App application is run the field values in the Catalog instance found by using a criteria definition are output as shown in Figure 10-13.

7. Finding All Documents

The MongoOperations interface provides the overloaded findAll() method to find all documents from a collection as discussed in Table 10-11.

  1. In the findAll() method in App application first add some Catalog instances to the catalog collection.
  2. Subsequently find all documents of entity class type Catalog using the findAll(Class<T> entityClass) method. The findAll() method returns a List instance.
  3. Obtain a Iterator<Catalog> from the List instance using the iterator() method.

Iterator<Catalog> iter = list.iterator();

  1. Iterate over the result set using the hasNext() method in a while loop and obtain the Catalog instances in the result set.
  2. Output the field values in the Catalog instances using the get() methods for the fields defined in the Catalog class. The findAll() method in App class is as follows.

private static void findAll() {

createCatalogInstances();

ops.save(catalog1);

ops.save(catalog2);

List<Catalog> list = ops.findAll(Catalog.class);

Iterator<Catalog> iter = list.iterator();

while (iter.hasNext()) {

Catalog catalog = iter.next();

System.out.println(“Journal :  ”  +  catalog.getJournal());

System.out.println(“Publisher :   ”  + catalog.getPublisher());

System.out.println(“Edition  :  ”  +  catalog.getEdition());

System.out.println(“Title : ”   + catalog.getTitle());

System.out.println(“Author : ” + catalog.getAuthor());

}

}

When the App application is run the field values from all the Catalog instances get output to the Console as shown in Figure 10-14.

8. Finding Documents Using a Query

In the preceding sections we have found documents using findAll (to find all documents), findOne (to find a single document), and findById(to find by Id). The MongoOperations interface provides the overloaded find() methods to find document/s using a specific query. The find() methods return a List<T> instance and are discussed in Table 10-12.

In the find() method in the App application we shall find documents in which the publisher field value is Oracle Publishing.

  1. Create a BasicDBObject instance using the constructor BasicDBObject(String key, Object value) with key as publisher and value as Oracle Publishing.

DBObject dbObject = new BasicDBObject(“publisher,” “Oracle Publishing”);

  1. Create a BasicQuery object from the BasicDBObject object using constructor BasicQuery(com.mongodb.DBObject queryObject).

BasicQuery query = new BasicQuery(dbObject);

  1. Using the BasicQuery instance invoke the find(Query query, Class<T> entityClass, String collectionName) method to find documents for the specified query. The find() method returns a List<Catalog> instance of documents.

List<Catalog> list = ops.find(query, Catalog.class, “catalog”);

  1. Obtain an iterator from the List instance and iterate over the List instance to output the field values from the documents in the list. The find() method in App application is as follows.

private static void find() {

createCatalogInstances();

ops.save(catalog1);

ops.save(catalog2);

DBObject dbObject = new BasicDBObject(“publisher”, “Oracle Publishing”);

BasicQuery query = new BasicQuery(dbObject);

List<Catalog> list = ops.find(query, Catalog.class, “catalog”);

Iterator<Catalog> iter = list.iterator();

while (iter.hasNext()) {

Catalog catalog = iter.next();

System.out.println(“Journal : ” + catalog.getJournal());

System.out.println(“Publisher : ” + catalog.getPublisher());

System.out.println(“Edition : ” + catalog.getEdition());

System.out.println(“Title : ” + catalog.getTitle());

System.out.println(“Author : ” + catalog.getAuthor());

}

  1. Run the App application to output the field values from the documents found using the find(Ouery query, Class<T> entityClass, String collectionName) method as shown in Figure 10-15.

  1. As was discussed for the findOne(Query query, Class<T> entityClass) method a criteria definition may also be used to find documents. Create a Criteria using the where and is method invocations in sequence to create a Criteria instance for journal field value as Oracle Magazine. Create a Query instance from the Criteria instance and invoke the find() method using the Query instance and the Catalog.class entity class type.

List<Catalog> list = ops.find(new Query(Criteria.where(“journal”).is(“Oracle Magazine”)),Catalog.class);

  1. Iterate over the list returned by the find method to output the field values for the Catalog instances in the list. The output from the find() method using a criterion is shown in Eclipse Console in Figure 10-16.

9. Updating the First Document

In this section we shall update a document using a query to find the document to update. A query could return multiple documents. If only the first document in the query result is to be updated the MongoOperations interface provides the overloaded updateFirst() method. The org.springframework. data.mongodb.core.query.Update class is used to provide the update clauses. Each of the updateFirst() methods, detailed in Table 10-13, returns a WriteResult object.

  •   Remove any previously added documents using the db.catalog.drop() method in Mongo shell.
  • In the updateFirst() method in App class save some Catalog instances using the createCatalogInstances() method to create the Catalog instances and the save() method to save the Catalog instances.
  • Create a BasicDBObject instance for edition field as key and November- December 2013 as value.

DBObject dbObject = new BasicDBObject(“edition”,”November-December 2013″);

  • Create a BasicQuery instance from the BasicDBObject instance.

BasicQuery query = new BasicQuery(dbObject);

  •   Invoke the updateFirst(Query query, Update update, Class<?> entityClass) method using the BasicQuery object as the first argument. Create the Update object for the second argument using the Update class static method update(String key, Object value) with key as edition and value as 11-12­2013, which implies that the edition field is to be updated to 11-12-2013. For the third argument specify Catalog.class. Output the WriteResult object returned by the updateFirst() method.

WriteResult result = ops.updateFirst(query,Update.update(“edition”, “11-12-2013”), Catalog.class);

System.out.println(result);

  • Subsequent to updating invoke the findAll(Class<T> entityClass) method to find all the documents, iterate over the list of documents found and output their field values.

List<Catalog> list = ops.findAll(Catalog.class);

Iterator<Catalog> iter = list.iterator();

while (iter.hasNext()) {

Catalog catalog = iter.next();

System.out.println(“Journal : ” + catalog.getJournal());

System.out.println(“Publisher : ” + catalog.getPublisher());

System.out.println(“Edition : ” + catalog.getEdition());

System.out.println(“Title : ” + catalog.getTitle());

System.out.println(“Author : ” + catalog.getAuthor());

}

The updateFirst() method in the App class is as follows.

private static void updateFirst() {

createCatalogInstances();

ops.save(catalog1);

ops.save(catalog2);

DBObject dbObject = new BasicDBObject(“edition”,

“November-December 2013”);

BasicQuery query = new BasicQuery(dbObject);

WriteResult result = ops.updateFirst(query,

Update.update(“edition”, “11-12-2013”), Catalog.class);

System.out.println(result);

List<Catalog> list = ops.findAll(Catalog.class);

Iterator<Catalog> iter = list.iterator();

while (iter.hasNext()) {

Catalog catalog = iter.next();

System.out.println(“Journal : ” + catalog.getJournal());

System.out.println(“Publisher : ” + catalog.getPublisher());

System.out.println(“Edition : ” + catalog.getEdition());

System.out.println(“Title : ” + catalog.getTitle());

System.out.println(“Author : ” + catalog.getAuthor());

}

}

When the App application is run to invoke the updateFirst() method the first document gets updated and subsequent listings of the documents found using the find() method include the edition field in the first document updated to 11-12-2013 as was specified in the update document as shown in Figure 10-17. The other documents still have the edition field as November-December 2013. The WriteResult field n has value 1, which implies that one document has been updated.

The query may also be specified using a criteria definition as follows.

WriteResult result = ops.updateFirst(new Ouery(Criteria.where(“edition”).is(“November- December 2013”)), Update.update(“edition”, “11-12-2013”), Catalog.class);

10. Update Multiple Documents

If multiple documents are to be updated the MongoOperations interface provides the overloaded updateMulti() method as discussed in Table 10-14.

Next, we shall update multiple documents in the catalog collection in the App class method updateMulti().

  1. Drop the catalog collection using the db.catalog.drop() method in Mongo shell.
  2. Create new documents using the createCatalogInstances() method and save the documents using the save() method.
  3. Create a BasicQuery object for the query document. The query document selects all documents with edition field as November-December 2013.

DBObject dbObject = new BasicDBObject(“edition”,”November-December 2013″);

BasicQuery query = new BasicQuery(dbObject);

  1. Invoke the updateMulti(Query query, Update update, Class<?> entityClass) method with the BasicQuery object as the first argument. Create a Update instance for edition field with value 11-12-2013 using the static method update(String key, Object value) for the second argument. Use entity class Catalog.class for the third argument. Output the WriteResult object returned by the updateMulti() method.

WriteResult result = ops.updateMulti(query,Update.update(“edition”, “11-12-2013”), Catalog.class);

System.out.println(result);

  1. Subsequently invoke the findAll() method to find and output field values from all the documents to verify that the documents got updated. The updateMulti() method is as follows.

private static void updateMulti() {

createCatalogInstances();

ops.save(catalog1);

ops.save(catalog2);

DBObject dbObject = new BasicDBObject(“edition”,

“November-December 2013”);

BasicQuery query = new BasicQuery(dbObject);

WriteResult result = ops.updateMulti(query,

Update.update(“edition”, “11-12-2013”), Catalog.class);

System.out.println(result);

List<Catalog> list = ops.findAll(Catalog.class);

Iterator<Catalog> iter = list.iterator();

while (iter.hasNext()) {

Catalog catalog = iter.next();
System.out.println(“Journal : ” + catalog.getJournal());
System.out.println(“Publisher : ” + catalog.getPublisher());
System.out.println(“Edition : ” + catalog.getEdition());
System.out.println(“Title : ” + catalog.getTitle());
System.out.println(“Author : ” + catalog.getAuthor());

}

}

  1. Drop any previously added catalog collection with the db.catalog.drop() method in Mongo shell.

When the App application is run to invoke the updateMulti() method, all documents for the specified query get updated. Subsequent invocation of findAll() lists the modified documents in which the edition field has been updated in all the documents, not just the first document as shown in Figure 10-18.

The query document in the updateMulti() method invocation may also be created using a criteria definition as follows.

WriteResult result = ops.updateMulti(new Ouery(Criteria.where(“edition”).is(“November- December 2013”)), Update.update(“edition”, “11-12-2013”), Catalog.class);

11. Removing Documents

In this section we shall remove documents from the catalog collection. The MongoOperations interface provides the overloaded remove() methods to remove documents for a specified query as discussed in Table 10-15.

The MongoOperations interface also provides the overloaded findAndRemove() method to find and remove a single document as discussed in Table 10-16

First, we shall look at an example using the remove() method.

  1. In the custom remove() class method in the App application (not to be confused with the remove() method in the MongoOperations interface), create and save two Catalog instances.
  2. Create a BasicDBObject instance using the _id field as key and id field value in the catalog1 instance as value. Create a BasicQuery instance using the BasicDBObject instance.

DBObject dbObject = new BasicDBObject(“_id”, catalog1.getId());

BasicQuery query = new BasicQuery(dbObject);

  1. Invoke one of the remove() methods to remove all the documents that match the specified query. Output the result of the remove() method.

WriteResult result = ops.remove(query, Catalog.class);

//WriteResult result = ops.remove(query, “catalog”);

//WriteResult result =ops.remove(query, Catalog.class, “catalog”);

System.out.println(result);

  1. Subsequently invoke the findAll() method to find and list all the documents. When the App application is run to invoke the remove() method the documents that match the given query get removed. For the example, one of the two documents gets removed and the other gets listed with findAll() as shown in Figure 10-19.

  1. To remove all documents the following query may be used.

DBObject dbObject = new BasicDBObject(“edition”,”November-December 2013″);

BasicOuery query = new BasicOuery(dbObject);

When the remove() method is invoked with the preceding query the two documents added get removed as indicated by the n field value of 2 as shown in Figure 10-20.

The remove() method in App application is as follows.

private static void remove() {

createCatalogInstances();

ops.save(catalogl);

ops.save(catalog2);

//DBObject dbObject = new BasicDBObject(“edition”,”November-December 2013″);

DBObject dbObject = new BasicDBObject(“_id”, catalog1.getId());

BasicQuery query = new BasicQuery(dbObject);

WriteResult result = ops.remove(query, Catalog.class);

// WriteResult result = ops.remove(query, “catalog”);

System.out.println(result);

List<Catalog> list = ops.findAll(Catalog.class);

Iterator<Catalog> iter = list.iterator(); while (iter.hasNext()) {

Catalog catalog = iter.next();
System.out.println(“Journal : ” + catalog.getJournal());
System.out.println(“Publisher : ” + catalog.getPublisher());
System.out.println(“Edition : ” + catalog.getEdition());
System.out.println(“Title : ” + catalog.getTitle());
System.out.println(“Author : ” + catalog.getAuthor());

}

}

Next, we shall demonstrate the findAndModify() method.

  1. Create a BasicQuery object to find all documents with a specific the _id field value. The query should return only one document as the _id field value is unique.

DBObject dbObject = new BasicDBObject(“_id”, catalog1.getId());

BasicQuery query = new BasicQuery(dbObject);

  1. Invoke one of the findAndRemove() methods using the query.

Catalog catalog = ops.findAndRemove(query, Catalog.class);

//Catalog catalog = ops.findAndRemove(query, Catalog.class, “catalog”);

  1. The findAndRemove() method returns the document that is found and removed. Output the field values from the removed document. When the App application is run the document matching the query is removed and its field values are output to the Eclipse Console as shown in Figure 10-21.

The App application is listed below with some of the method invocations and code sections commented out. Uncomment the code sections to test before running the application.

package com.mongo.core;

import java.util.ArrayList; import java.util.Iterator;

import java.util.List; import org.bson.types.ObjectId;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.mongo.config.SpringMongoApplicationConfig;

import org.springframework.data.mongodb.core.MongoOperations;

import org.springframework.data.mongodb.core.query.BasicQuery;

import org.springframework.data.mongodb.core.query.Criteria;

import org.springframework.data.mongodb.core.query.Query;

import org.springframework.data.mongodb.core.query.Update;

import com.mongo.model.Catalog;

import com.mongodb.BasicDBObject;

import com.mongodb.DBObject;

import com.mongodb.WriteResult;

public class App {

static MongoOperations ops;

static Catalog catalog1;

static Catalog catalog2;

public static void main(String[] args) {

ApplicationContext context = new AnnotationConfigApplicationContext(

SpringMongoApplicationConfig.class);

ops = context.getBean(“mongoTemplate”, MongoOperations.class);

// createCollection();

// createCatalogInstances();

// addDocument();

// updateFirst();

// updateMulti();

// findById();

// findOne();

// findAll(); find();

// addDocumentBatch();

//remove();

}

private static void createCollection() {

if (!ops.collectionExists(“catalog”)) {

ops.createCollection(“catalog”);

} else {

ops.dropCollection(“catalog”);

ops.createCollection(“catalog”);

}

}

private static void createCatalogInstances() {

catalog1 = new Catalog(“catalog1”, “Oracle Magazine”,

“Oracle Publishing”, “November-December 2013”,

“Engineering as a Service”, “David A. Kelly”);

catalog2 = new Catalog(“catalog2”, “Oracle Magazine”,

“Oracle Publishing”, “November-December 2013”,

“Quintessential and Collaborative”, “Tom Haunert”);

}

private static void addDocument() {

catalogl = new Catalog(“catalog1”, “Oracle Magazine”,

“Oracle Publishing”, “November-December 2013”,

“Engineering as a Service”, “David A. Kelly”);

// ops.save(catalog1, “catalog”);//collection created implicitly ops.save(catalog1);

// collection created implicitly by same name as // object class

System.out.println(“MongoDB generated Id: ” + catalog1.getId());

catalog2 = new Catalog(“catalog2”, “Oracle Magazine”,

“Oracle Publishing”, “November-December 2013”,

“Quintessential and Collaborative”, “Tom Haunert”);

ops.save(catalog2, “catalog”);

System.out.println(“MongoDB generated Id: ” + catalog2.getId());

}

private static void addDocumentBatch() {

catalog1 = new Catalog(“catalog1”, “Oracle Magazine”,

“Oracle Publishing”, “November-December 2013”,

“Engineering as a Service”, “David A. Kelly”);

catalog2 = new Catalog(“catalog2”, “Oracle Magazine”,

“Oracle Publishing”, “November-December 2013”,

“Quintessential and Collaborative”, “Tom Haunert”);

ArrayList arrayList = new ArrayList();

arrayList.add(catalog1);

arrayList.add(catalog2);

ops.insert(arrayList, “catalog”);

// ops.insert(arrayList,Catalog.class);

// ops.insertAll(arrayList);

}

private static void findById() {

catalog1 = new Catalog(“catalog1”, “Oracle Magazine”,

“Oracle Publishing”, “November-December 2013”,

“Engineering as a Service”, “David A. Kelly”);

ops.save(catalog1);

// Catalog catalog = ops.findById(catalog1.getId(),

// Catalog.class,”catalog”);

Catalog catalog = ops.findById(catalog1.getId(), Catalog.class);

System.out.println(“Id in Catalog instance: ” + catalog1.getId());

System.out.println(“Journal : ” + catalog.getJournal());

System.out.println(“Publisher : ” + catalog.getPublisher());

System.out.println(“Edition : ” + catalog.getEdition());

System.out.println(“Title : ” + catalog.getTitle());

System.out.println(“Author : ” + catalog.getAuthor());

}

private static void findOne() {

createCatalogInstances();

ops.save(catalog1);

ops.save(catalog2);

/*

* String _id = catalog2.getId(); Catalog catalog = ops.findOne(new

* Query(Criteria.where(“_id”).is(_id)), Catalog.class);

* out.println(“Id in Catalog instance: ” + catalog2.getId());

* out.println(“Journal : ” + catalog.getJournal());

* out.println(“Publisher : ” + catalog.getPublisher());

* out.println(“Edition : ” + catalog.getEdition());

* out.println(“Title : ” + catalog.getTitle());

* out.println(“Author : ” + catalog.getAuthor());

*/

DBObject dbObject = new BasicDBObject(“id”, new ObjectId( catalog1.getId()));

BasicQuery query = new BasicQuery(dbObject);

Catalog catalog = ops.findOne(query, Catalog.class);

catalog = ops.findOne(query, Catalog.class, “catalog”);

System.out.println(“Id in Catalog instance: ” + catalog1.getId());

System.out.println(“Journal : ” + catalog.getJournal());

System.out.println(“Publisher : ” + catalog.getPublisher());

System.out.println(“Edition : ” + catalog.getEdition());

System.out.println(“Title : ” + catalog.getTitle());

System.out.println(“Author : ” + catalog.getAuthor());

}

private static void findAll() {

createCatalogInstances();

ops.save(catalog1);

ops.save(catalog2);

List<Catalog> list = ops.findAll(Catalog.class);

Iterator<Catalog> iter = list.iterator();

while (iter.hasNext()) {

Catalog catalog = iter.next();

System.out.println(“Journal : ” + catalog.getJournal());

System.out.println(“Publisher : ” + catalog.getPublisher());

System.out.println(“Edition : ” + catalog.getEdition());

System.out.println(“Title : ” + catalog.getTitle());

System.out.println(“Author : ” + catalog.getAuthor());

}

}

private static void find() {

createCatalogInstances();

ops.save(catalogl);

ops.save(catalog2);

/*DBObject dbObject = new BasicDBObject(“publisher”, “Oracle Publishing”);

BasicOuery query = new BasicOuery(dbObject);

List<Catalog> list = ops.find(query, Catalog.class, “catalog”);*/

List<Catalog> list = ops.find(

new Ouery(Criteria.where(“journal”).is(“Oracle Magazine”)), Catalog.class);

Iterator<Catalog> iter = list.iterator(); while (iter.hasNext()) {

Catalog catalog = iter.next();

System.out.println(“Journal : ” + catalog.getJournal());

System.out.println(“Publisher : ” + catalog.getPublisher());

System.out.println(“Edition : ” + catalog.getEdition());

System.out.println(“Title : ” + catalog.getTitle());

System.out.println(“Author : ” + catalog.getAuthor());

}

}

private static void updateFirst() {

createCatalogInstances();

ops.save(catalogl);

ops.save(catalog2);

WriteResult result = ops.updateFirst(new Ouery(Criteria

.where(“edition”).is(“November-December 2013”)), Update.update(

“edition”, “11-12-2013”), Catalog.class);

System.out.println(result);

List<Catalog> list = ops.findAll(Catalog.class);

Iterator<Catalog> iter = list.iterator(); while (iter.hasNext()) {

Catalog catalog = iter.next();

System.out.println(“Journal : ” + catalog.getJournal());

System.out.println(“Publisher : ” + catalog.getPublisher());

System.out.println(“Edition : ” + catalog.getEdition());

System.out.println(“Title : ” + catalog.getTitle());

System.out.println(“Author : ” + catalog.getAuthor());

}

/*
* DBObject dbObject = new BasicDBObject(“edition”,
* “November-December 2013”); BasicQuery query = new
* BasicQuery(dbObject); WriteResult result = ops.updateFirst(query,
* Update.update(“edition”, “11-12-2013”), Catalog.class);
* System.out.println(result);
*

* List list = ops.findAll(Catalog.class); Iterator

* iter = list.iterator(); while (iter.hasNext()) { Catalog catalog =

* iter.next(); System.out.println(“Journal : ” + catalog.getJournal());

* System.out.println(“Publisher : ” + catalog.getPublisher());

* System.out.println(“Edition : ” + catalog.getEdition());

* System.out.println(“Title : ” + catalog.getTitle());

* System.out.println(“Author : ” + catalog.getAuthor()); }

*/

}

private static void updateMulti() {

createCatalogInstances();

ops.save(catalog1);

ops.save(catalog2);

DBObject dbObject = new BasicDBObject(“edition”,

“November-December 2013”);

BasicQuery query = new BasicQuery(dbObject);

WriteResult result = ops.updateMulti(query,

Update.update(“edition”, “11-12-2013”), Catalog.class);

System.out.println(result);

List<Catalog> list = ops.findAll(Catalog.class);

Iterator<Catalog> iter = list.iterator(); while (iter.hasNext()) {

Catalog catalog = iter.next();

System.out.println(“Journal : ” + catalog.getJournal());

System.out.println(“Publisher : ” + catalog.getPublisher());

System.out.println(“Edition : ” + catalog.getEdition());

System.out.println(“Title : ” + catalog.getTitle());

System.out.println(“Author : ” + catalog.getAuthor());

}

/*

* WriteResult result = ops.updateMulti(new Query(Criteria
* .where(“edition”).is(“November-December 2013”)), Update.update(
* “edition”, “11-12-2013”), Catalog.class); System.out.println(result);
* findAll();

*/

}

private static void remove() {

createCatalogInstances();

ops.save(catalog1);

ops.save(catalog2);

DBObject dbObject = new BasicDBObject(“_id”, catalog1.getId());

BasicQuery query = new BasicQuery(dbObject);

Catalog catalog = ops.findAndRemove(query, Catalog.class);

// Catalog catalog = ops.findAndRemove(query, Catalog.class, “catalog”);

System.out.println(“Journal : ” + catalog.getJournal());

System.out.println(“Publisher : ” + catalog.getPublisher());

System.out.println(“Edition : ” + catalog.getEdition());

System.out.println(“Title : ” + catalog.getTitle());

System.out.println(“Author : ” + catalog.getAuthor());

/*

* DBObject dbObject = new
* BasicDBObject(“edition”,”November-December 2013″); //DBObject
* dbObject = new BasicDBObject(“_id”, catalog1.getId()); BasicQuery
* query = new BasicQuery(dbObject); // WriteResult result =
* ops.remove(query,Catalog.class); WriteResult result =
* ops.remove(query, “catalog”); System.out.println(result);

*/

/*List<Catalog> list = ops.findAll(Catalog.class);

Iterator<Catalog> iter = list.iterator();

while (iter.hasNext()) {

catalog = iter.next();

System.out.println(“Journal : ” + catalog.getJournal());

System.out.println(“Publisher : ” + catalog.getPublisher());

System.out.println(“Edition : ” + catalog.getEdition());

System.out.println(“Title : ” + catalog.getTitle());

System.out.println(“Author : ” + catalog.getAuthor());

}*/

}

}

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 *