Using a Java Client with MongoDB: Creating a BSON Document

In this section we shall add a BSON (Binary JSON) document to MongoDB server. We shall use the CreateMongoDBDocument.java application in Eclipse IDE. A MongoDB document is represented with the org.bson.Document class. MongoDB stores data in collections. The main packages for MongoDB classes in the MongoDB Java driver are com.mongodb and com.mongodb.client. A MongoDB client to connect to MongoDB server is represented with the com.mongodb.MongoClient class. A MongoClient object provides connection pooling, and only one instance is required for the entire instance. The MongoClient class provides several constructors, some of which are listed in Table 1-2.

  1. Create a MongoClient instance using the MongoClient(List<ServerAddress> seeds) constructor. Supply “localhost’’ or the IPv4 address of the host and port as 27017.

MongoClient mongoClient = new MongoClient

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

  1. When creating many MongoClient instances, all resource usage limits apply per MongoClient instance. To close an instance you need to call MongoClient. close() to clean up resources. A logical database in MongoDB is represented with the com.mongodb.client.MongoDatabase interface. Obtain a com.mongodb.client.MongoDatabase instance for the “local” database, which is a default MongoDB database instance, using the getDatabase(String databaseName) method in MongoClient class.

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

  1. Some of the Mongo client API has been modified in version 3.0.x. For example, a database instance is represented with the MongoDatabase in 3.0.x instead of com.mongodb.DB. The getDB(String dbName) method, which returns a DB instance, in MongoClient is deprecated. A database collection in 3.0.x is represented with com.mongodb.client.MongoCollection<TDocument> instead of com.mongodb.DBCollection. Get all collections from the database instance using the listCollectionNames() method in MongoDatabase.

MongoIterable<String> colls = db.listCollectionNames();

  1. The listCollectionNames() method returns a MongoIterable<String> of collections. Iterate over the collection to output the collection names.

for (String s : colls) {

System.out.println(s);

}

  1. Next, create a new MongoCollection<Document>instance using the getCollection(String collectionName) method in MongoDatabase. Create a collection of Document instances called catalog. A collection gets created implicitly when the getCollection(String) method is invoked.

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

A MongoDB specific BSON object is represented with the org.bson.Document class, which implements the Map interface among others. The Document class provides the following constructors listed in Table 1-3 to create a new instance.

The Document class provides some other utility methods, some of which are in Table 1-4.

  1. Create a Document instance using the Document(String key, Object value) constructor and use the append(String key, Object value) method to append key/value pairs. The append() method may be invoked multiple times in sequence to add multiple key/value pairs. Add key/value pairs for the journal, publisher, edition, title, and author fields.

Document catalog = new Document(“journal”, “Oracle Magazine”)

.append(“publisher”, “Oracle Publishing”)

.append(“edition”, “November December 2013”)

.append(“title”, “Engineering as a Service”).append(“author”,

“David A. Kelly”);

  1. The MongoCollection<TDocument> interface provides insertOne(TDocument document) method to add a document(s) to a collection. Add the catalog Document to the MongoCollection<TDocument> instance for the catalog collection.

coll.insertOne(catalog);

  1. The MongoCollection<TDocument> interface provides overloaded find() method to find a Document instance. Next, obtain the document added using the find() method. Furthermore, the find() method returns an iterable collection from which we obtain the first document using the first() method.

Document dbObj = coll.find().first();

  1. Output the Document object found as such and also by iterating over the Set<E> obtained from the Document using the keySet() method. The keySet() method returns a Set<String>. Create an Iterator from the Set<String> using the iterator() method. While the Iterator has elements as determined by the hasNext() method, obtain the elements using the next() method. Each element is a key in the Document fetched. Obtain the value for the key using the get(String key) method in Document.

System.out.println(dbObj);

Set<String> set = dbObj.keySet();

Iterator iter = set.iterator();

while(iter.hasNext()){

Object obj= iter.next();

System.out.println(obj);

System.out.println(dbObj.get(obj.toString()));

}

  1. Close the MongoClient instance.

mongoClient.close();

The CreateMongoDBDocument class is listed below.

package mongodb;

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.MongoCollection;

import com.mongodb.client.MongoDatabase;

import com.mongodb.client.MongoIterable;

public class CreateMongoDBDocument {

public static void main(String[] args) {

MongoClient mongoClient = new MongoClient(

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

for (String s : mongoClient.listDatabaseNames()) {

System.out.println(s);

}

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

MongoIterable<String> colls = db.listCollectionNames();

System.out.println(“MongoDB Collection Names: “);

for (String s : colls) {

System.out.println(s);

}

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

Document catalog = new Document(“journal”, “Oracle Magazine”)

.append(“publisher”, “Oracle Publishing”)

.append(“edition”, “November December 2013”)

.append(“title”, “Engineering as a Service”)

.append(“author”, “David A. Kelly”);

coll.insertOne(catalog);

Document dbObj = coll.find().first(); System.out.println(dbObj);

Set<String> set = catalog.keySet();

Iterator<String> iter = set.iterator(); while (iter.hasNext()) {

Object obj = iter.next();

System.out.println(obj);

System.out.println(dbObj.get(obj.toString()));

}

mongoClient.close();

}

}

  1. To run the CreateMongoDBDocument application, right-click on the

CreateMongoDBDocument.java file in Package Explorer and select Run As ➤ Java Application as shown in Figure 1-11.

A new BSON document gets stored in a new collection catalog in MongoDB database. The document stored is also output as such and as key/value pairs as shown in Figure 1-12.

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 *