Using a Java Client with MongoDB: Using a Model to Create a BSON Document

In the previous section we constructed the documents to add to a collection using the append(String key, Object value) method in Document class and added the documents to a collection using the insertOne(TDocument document) method in MongoCollection<TDocument> interface. A Document object may also be constructed using a model class that represents the objects in a collection. The MongoCollection<TDocument> interface provides the overloaded insertMany() method to add a list of documents as discussed in Table 1-5.

In this section we shall construct a list of documents using a model class. Subsequently, we shall insert the list into a collection using one of the insertMany() methods.

  1. First, create a model class Catalog with the following fields:
  • catalogId
  • journal
  • publisher
  • edition
  • title
  • author
  1. The model class extends the BasicDBObject class, which is a basic implementation of a MongoDB specific BSON object, and implements the Serializable interface. The class implements the Serializable interface to serialize a model class object to a cache when persisted to a database.

To associate a version number with a serializable class by serialization runtime, specify a serialVersionUID variable with scope private.

private static final long serialVersionUID = 1L;

  1. Specify a class constructor that takes all the fields as args. The model class Catalog is listed below.

package mongodb;

import java.io.Serializable;

import com.mongodb.BasicDBObject;

public class Catalog extends BasicDBObject implements Serializable {

private static final long serialVersionUID = 1L;

private String catalogId;

private String journal;

private String publisher;

private String edition;

private String title;

private String author; public Catalog() {

super();

}

public Catalog(String catalogId, String journal, String publisher,

String edition, String title, String author) {

this.catalogId = catalogId;

this.journal = journal;

this.publisher = publisher;

this.edition = edition;

this.title = title;

this.author = author;

}

}

Next, we shall use the model class Catalog to construct documents and add the documents to MongoDB database. We shall use the CreateMongoDBDocumentModel class to construct and add documents to MongoDB.

  1. First, create a MongoClient instance as discussed previously.

MongoClient mongoClient = new MongoClient

(Arrays.asList(new ServerAddress(“localhost”, 27017)));

  1. Also create a MongoDatabase instance for the local database using the

getDatabase(String databaseName) method in MongoClient class.

MongoDatabase db = mongoClient.getDatabase(“local”);

The MongoDatabase interface provides the overloaded methods listed in Table 1-6 for getting or creating a collection represented with the MongoCollection<TDocument> interface.

  1. Create a collection from the MongoDatabase instance created earlier using the getCollection(String collectionName) method.

MongoCollection<Document> coll = db.getCollection(“catalog”);

  1. As the Catalog class extends the BasicDBObject class it also represents a document object that may be stored in MongoDB database. Create instances of Catalog and set the object fields using the put(String key,Object value) method in BasicDBObject class.

Catalog catalog1 = new Catalog();

catalog1.put(“catalogId”, “catalog1”);

catalog1.put(“journal”, “Oracle Magazine”);

catalog1.put(“publisher”, “Oracle Publishing”);

catalog1.put(“edition”, “November December 2013”);

catalog1.put(“title”, “Engineering as a Service”);

catalog1.put(“author”, “David A. Kelly”);

Catalog catalog2 = new Catalog();

catalog2.put(“catalogId”, “catalog2”);

catalog2.put(“journal”, “Oracle Magazine”);

catalog2.put(“publisher”, “Oracle Publishing”);

catalog2.put(“edition”, “November December 2013”);

catalog2.put(“title”, “Quintessential and Collaborative”);

catalog2.put(“author”, “Tom Haunert”);

  1. Create a Document instance and add the Catalog objects to the Document as key/ value pairs using the append(String key, Object value) method.

Document documentSet = new Document();

documentSet.append(“catalog1”, catalog1);

documentSet.append(“catalog2”, catalog2);

  1. As the argument to the insertMany() method for adding documents is required to be of type List<E> we need to create a List<E> instance using a ArrayList<E> constructor.

ArrayList<Document> arrayList = new ArrayList<Document>();

  1. Add the Document instance with key/value pairs added to it to the ArrayList<E> using the add(E e) method.

arrayList.add(documentSet);

  1. Add the ArrayList<E> instance to the MongoCollection<TDocument> instance using the insertMany(List<? extends TDocument> documents) method.

coll.insertMany(arrayList);

  1. To verify that the documents have been added get the documents using the find() method in MongoCollection<TDocument> The find() method returns as the result a FindIterable<TDocument> object.

FindIterable<Document> iterable = coll.find();

Subsequently, output the key/value pairs stored in the FindIterable<TDocument> object. Using an enhanced for loop obtain the Document instances in the FindIterable<TDocument> and obtain the key set associated with each Document instance using the keySet() method, which returns a Set<String> object. Create an iterator represented with an Iterator<String> object using the iterator() method in Set<E>. Using a while loop iterate over the key set to output the document key for each Document and the associated Document object.

FindIterable<Document> iterable = coll.find();

String documentKey = null;

for (Document document : iterable) {

Set<String> keySet = document.keySet();

Iterator<String> iter = keySet.iterator();

while (iter.hasNext()) {

documentKey = iter.next();

System.out.println(documentKey);

System.out.println(document.get(documentKey));

}

}

    1. Close the MongoClient object using the close()

method. mongoClient.close();

The CreateMongoDBDocumentModel class is listed below.

package mongodb;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Iterator;

import java.util.Set;

import org.bson.Document;

import com.mongodb.MongoClient;

import com.mongodb.ServerAddress;

import com.mongodb.client.FindIterable;

import com.mongodb.client.MongoCollection;

import com.mongodb.client.MongoDatabase;

public class CreateMongoDBDocumentModel {

public static void main(String[] args) {

MongoClient mongoClient = new MongoClient(

Arrays.asList(new ServerAddress(“localhost”, 27017)));

MongoDatabase db = mongoClient.getDatabase(“local”);

MongoCollection<Document> coll = db.getCollection(“catalog”);

Catalog catalog1 = new Catalog();

catalog1.put(“catalogId”, “catalog1”);

catalog1.put(“journal”, “Oracle Magazine”);

catalog1.put(“publisher”, “Oracle Publishing”);

catalog1.put(“edition”, “November December 2013”);

catalog1.put(“title”, “Engineering as a Service”);

catalog1.put(“author”, “David A. Kelly”);

 

Catalog catalog2 = new Catalog();

catalog2.put(“catalogId”, “catalog2”);

catalog2.put(“journal”, “Oracle Magazine”);

catalog2.put(“publisher”, “Oracle Publishing”);

catalog2.put(“edition”, “November December 2013”);

catalog2.put(“title”, “Quintessential and Collaborative”);

catalog2.put(“author”, “Tom Haunert”);

 

Document documentSet = new Document();

documentSet.append(“catalog1”, catalog!.);

documentSet.append(“catalog2”, catalog2);

ArrayList<Document> arrayList = new ArrayList<Document>();

arrayList.add(documentSet);

coll.insertMany(arrayList);

FindIterable<Document> iterable = coll.find();

String documentKey = null;

for (Document document : iterable) {

Set<String> keySet = document.keySet();

Iterator<String> iter = keySet.iterator();

while (iter.hasNext()) {

documentKey = iter.next();

System.out.println(documentKey);

System.out.println(document.get(documentKey));

}

}

mongoClient.close();

}

}

Next, run the CreateMongoDBDocumentModel application. Before running the application drop the catalog collection using db.catalog.drop() in mongo shell as we shall be creating an empty catalog collection in the application to add documents. Right-click on the CreateMongoDBDocumentModel.java file in Package Explorer and select Run As ➤ Java Application as shown in Figure 1-13.

One document gets added to the MongoDB collection catalog as indicated by the one _id fetched. The document added has two key/value pairs. Subsequently, the key/value pairs for the Catalog instances added get output as shown in Figure 1-14. The _id would most likely be different than what is shown in Figure 1-14 as it is generated automatically.

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 *