Hour 12. Working with MongoDB Data in Java Applications


What You’ll Learn in This Hour:

Image Inserting new documents into a collection from Java

Image Removing documents from a collection in Java

Image Getting, manipulating, and saving a single document in a collection from Java

Image Updating documents in a collection from Java

Image Performing an upsert operation from Java


This hour continues the last hour’s description of the Java MongoDB driver and tells how to implement it to add, manipulate, and remove documents from a collection in your Java applications. You have several methods for changing data in a collection. You can insert new documents, update existing documents using update or save, remove old documents, and apply an upsert (which first tries to update documents and, if none is found, inserts a new one).

The following sections cover the various methods on the Java DBCollection object that enable you to manipulate data in the collection. You see how to insert, delete, save, and update documents in a collection from your Java application.

Adding Documents from Java

An important task when interacting with MongoDB databases from Java is inserting documents into collections. To insert a document, you need to first create a BasicDBObject object that represents the document you want to store. Insert operations pass the BasicDBObject object to the MongoDB sever as a BSON that can be inserted into the collections.

When you have a BasicDBObject version of your new document, you can store it in the MongoDB database using the insert() method on an instance of the DBCollection object that is connected to the database. The following shows the syntax for the insert() method, where the docs parameter can be a single document object or an array of document objects:

insert(docs)

For example, the following shows an example of inserting a single document and an array of documents into a collection:

BasicDBObject doc1 = new BasicDBObject("name", "Fred");
WriteResult result = myColl.insert(doc1);
BasicDBObject doc2 = new BasicDBObject("name", "George");
BasicDBObject doc3 = new BasicDBObject("name", "Ron");
WriteResult result = myColl.insert(new BasicDBObject[]{doc2, doc3});

Notice that the insert() method returns a WriteResult object that contains information about the write operation.

Removing Documents from Java

Sometimes you need to delete documents from your MongoDB collection from Java to keep space consumption down, improve performance, and keep things clean. The remove() method on DBCollection objects makes it simple to delete documents from a collection. The syntax for the remove() method follows:

remove([query])

The query parameter is a BasicDBObject object that identifies which document(s) you want to delete. The request matches the fields and values in the query with the fields and values of the object, and only those that match the query are updated. If no query is provided, all the documents in the collection are deleted.

For example, to delete all documents in the words_stats collection, you could use

DBCollection collection = myDB.getCollection('word_stats');
WriteResult results = collection.remove();

The following code deletes all words that start with a from the words_stats collection:

DBCollection collection = myDB.getCollection('word_stats');
BasicDBObject query = new BasicDBObject("first", "a");
collection.remove(query);

Saving Documents from Java

A convenient method of updating objects in the database is to use the save() method on DBCollection objects. The save method accepts a DBObject as a parameter and saves it to the database. If the document already exists in the database, it is updated with the new values. If the document does not already exist in the database, a new document is created.

The following shows the syntax of the save() method, where the doc parameter is the DBObject or BasicDBObject object to be saved to the collection:

save(doc)

Updating Documents from Java

After objects have been inserted into a collection, you often need to update them from Java as data changes. The update() method on the DBCollection object enables you to update documents in a collection. The update method is versatile yet fairly easy to implement. The syntax for the update() method follows:

update(query, update, [upsert], [multi])

The query parameter is a BasicDBObject object that identifies which document(s) you want to change. The request matches the properties and values in the query with the fields and values of the object, and only those that match the query are updated. The update parameter is a BasicDBObject that specifies the changes to make to the documents that match the query. Hour 8, “Manipulating MongoDB Documents in a Collection,” describes the update operators used in this object.

The upsert parameter is a Boolean. When true, if no objects match the query, a new document is created. The multi parameter is also a Boolean; when true, all documents that match the query are updated. When multi is false, only the first document that matches the query is updated.

For example, the following changes the category field value to old for items in the collection, where category currently is new. With upsert set to false, new documents are not created even if no documents have a category of new; with multi set to true, all documents that match are updated:

BasicDBObject query = new BasicDBObject("category", "New");
BasicDBObject update = new BasicDBObject("$set",
    new BasicDBObject("category", "Old"));
update(query, update, false, true);

Upserting Documents from Java

Another way to use the update() method on the DBCollection object in Java is for upsert operations. An upsert operation first tries to update documents in the collection. If no documents match the update query, the $set operator is used to create a new document and add it to the collection. The following shows the syntax for the update() method:

update(query, update, [upsert], [multi])

The query parameter identifies which document(s) you want to change. The update parameter is a BasicDBObject that specifies the changes to make to the documents that match the query. For upsert operations, the upsert parameter should be set to true and the multi parameter should be set to false.

For example, the following performs an upsert on a document with name=myDoc. The $set operator defines the fields used to create or update the document. With upsert set to true, if the document is not found, it is created; otherwise, it is updated:

BasicDBObject query = new BasicDBObject("name", "myDoc");
BasicDBObject setOp = new BasicDBObject("name", "myDoc");
setOp.append("number", 5);
setOp.append("score", 10);
BasicDBObject update = new BasicDBObject("$set", setOp);
update(query, update, true, false);

Summary

In this hour, you used the Java MongoDB driver to add, manipulate, and remove documents from a collection in your Java applications. You used several different methods on the DBCollection object to change data in a collection.

The insert() method adds new documents. The remove() method deletes documents. The save() method updates a single document.

The update() method can be used in multiple ways. You can have it update a single document or multiple documents. You can also apply the upsert option to insert new documents into the collection if none match to be updated.

Q&A

Q. Can you delete the entire collection and Collection object from Java?

A. Yes. You can call the drop() method on the DBCollection object.

Workshop

The workshop consists of a set of questions and answers designed to solidify your understanding of the material covered in this hour. Try answering the questions before looking at the answers.

Quiz

1. Which operation would you use from a Java application to create a new document if one does not exist?

2. How do you limit the update() method to only a single document?

3. True or false: You can use the save() method on Collection objects only to save existing documents?

4. What type of parameter defines the fields to update in the update() method of the DBCollection object?

Quiz Answers

1. Use the update() method on the DBCollection object with upsert set to true.

2. Set the multi parameter to false.

3. False. save() adds the document if it doesn’t exist.

4. It is a BasicDBObject that contains MongoDB update operators as fields.

Exercises

1. Find a new word that you want to add to the word_stats collection in the example dataset. Write a new Java application similar to JavaDocAdd.java file to add that word.

2. Create a new Java application that uses the update() method to update all words with first letter of e and add the category of eWords to them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.158.173