Java MongoDB Driver 3.3.0 - Update Document(s)

 Posted On  | Yashwant Chavan 

In this article we will learn how to update document using Java MongoDB Driver 3.3.0. MongoDB provides flexibility to update one or more documents within the collection based on the filter. Learn more about updateOne() and updateMany() methods with example.

Tools and Technologies

Basically we are using below maven dependencies

  1. Maven 3.0.4
  2. JDK 1.8
  3. Mongo Java Driver 3.3.0

Maven Dependencies

To use the mongodb java driver, Define respected maven dependencies of mongo-java-driver in pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.technicalkeeda</groupId>
    <artifactId>JavaExamples</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.3.0</version>
        </dependency>
    </dependencies>
</project>

Connecting to database

A MongoDB client internally uses the connection pooling mechanism. It has one MongoClient instance for the entire JVM. To connect the local mongoDb database use host name (localhost) and default port number (27017).

 MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));

Get the database instance

Once you are successfully connected, access the mongoDB database e.g.(technicalkeeda).

 MongoDatabase database = mongoClient.getDatabase("technicalkeeda");

Get the Collection

Get the collection and update document(s) into a collection named books. It will create the collection if the collection does not exist.

 MongoCollection<Document> books = database.getCollection("books");

Update One

In updateOne() example, We have modified three fields "title" , "price" and "authors.name". Where filter condition is set as book_id = 1. eq("book_id", "1"), Refer the mongoDB shell output.

Update a single document in the collection base on specified arguments. updateOne(Bson filter,Bson update) accept two parameters.

filter - a document describing the query filter, which may not be null.

update - a document describing the update, which may not be null. The update to apply must include only update operators.

To change a field value, MongoDB provides update operators, such as $set to modify values.

MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document. The following updateOne example the name field in the embedded authors document.

UpdateResult gives the result of an update operation.

 UpdateResult updateResult = books.updateOne(eq("book_id", "1"),new Document("$set", new Document("title", "**Updated** - One Indian Girl").append("price", "$18.00").append("authors.name", "**Update** - Chetan Bhagat")));
 System.out.println("Number of record updated:- " + updateResult.getModifiedCount());

Update Many

In updateMany() example, We have modified "title" field only. Where filter condition is set as book_id >= 2. gte("book_id", "2"), Refer the mongoDB shell output.

Update multiple documents within the collection based on the filter. The updateMany() method has the following form. Rest of the things like condition filter,update operators are same as we have used in updateOne() example.

getModifiedCount() return the number of documents modified by the update operation.

 updateResult = books.updateMany(gte("book_id", "2"),new Document("$set", new Document("title", "**Updated** - Book Title")));
 System.out.println("Number of record updated:- " + updateResult.getModifiedCount());

mongoDB Update Operators

  • $inc - Increments the value of the field by the specified amount.
  • $mul -Multiplies the value of the field by the specified amount.
  • $rename - Renames a field.
  • $setOnInsert - Sets the value of a field if an update results in an insert of a document. Has no effect on update operations that modify existing documents.
  • $set - Sets the value of a field in a document.
  • $unset - Removes the specified field from a document.
  • $min - Only updates the field if the specified value is less than the existing field value.
  • $max - Only updates the field if the specified value is greater than the existing field value.
  • $currentDate - Sets the value of a field to current date, either as a Date or a Timestamp.

mongoDB Update Full Example

package com.technicalkeeda.app;

import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.gte;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.UpdateResult;

public class App {
    public static void main(String[] args) {
        new App().update();
    }

    public void update() {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
        MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
        List < Document > booksList = new ArrayList < Document > ();

        try {
            MongoDatabase database = mongoClient.getDatabase("technicalkeeda");
            // using insertOne
            MongoCollection < Document > books = database.getCollection("books");

            booksList.add(
                new Document("authors", new Document().append("author_id", "1").append("name", "Chetan Bhagat"))
                .append("book_id", "1").append("title", "One Indian Girl").append("isbn", "8129142147")
                .append("price", "$14.99").append("publish_date", format.parse("2016-10-01T00:00:00Z")));

            booksList
                .add(new Document("authors", new Document().append("author_id", "2").append("name", "Sarina Singh"))
                    .append("book_id", "2").append("title", "Lonely Planet India").append("isbn", "1743216769")
                    .append("price", "$34.99").append("publish_date", format.parse("2015-10-01T00:00:00Z")));

            booksList.add(new Document("authors", new Document().append("author_id", "3").append("name", "John Keay"))
                .append("book_id", "3").append("title", "India: A History").append("isbn", "0802145582")
                .append("price", "$20.00").append("publish_date", format.parse("2011-04-01T00:00:00Z")));

            books.insertMany(booksList);

            UpdateResult updateResult = books.updateOne(eq("book_id", "1"),
                new Document("$set", new Document("title", "**Updated** - One Indian Girl")
                    .append("price", "$18.00").append("authors.name", "**Update** - Chetan Bhagat")));
            System.out.println("Number of record updated:- " + updateResult.getModifiedCount());

            updateResult = books.updateMany(gte("book_id", "2"),
                new Document("$set", new Document("title", "**Updated** - Book Title")));
            System.out.println("Number of record updated:- " + updateResult.getModifiedCount());

            MongoCursor < Document > cursor = books.find().iterator();

            try {
                while (cursor.hasNext()) {
                    Document book = cursor.next();
                    System.out.println(book);
                }
            } finally {
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mongoClient.close();
        }
    }
}

Program Output

Number of record updated:- 1
Number of record updated:- 2
Document{{_id=57e66baba3e9070470605b9c, authors=Document{{author_id=1, name=**Update** - Chetan Bhagat}}, book_id=1, title=**Updated** - One Indian Girl, isbn=8129142147, price=$18.00, publish_date=Sat Oct 01 00:00:00 IST 2016}}
Document{{_id=57e66baba3e9070470605b9d, authors=Document{{author_id=2, name=Sarina Singh}}, book_id=2, title=**Updated** - Book Title, isbn=1743216769, price=$34.99, publish_date=Thu Oct 01 00:00:00 IST 2015}}
Document{{_id=57e66baba3e9070470605b9e, authors=Document{{author_id=3, name=John Keay}}, book_id=3, title=**Updated** - Book Title, isbn=0802145582, price=$20.00, publish_date=Fri Apr 01 00:00:00 IST 2011}}

Shell Output

> use technicalkeeda
switched to db technicalkeeda
> show collections
books
system.indexes
> db.books.find().pretty()
{
        "_id" : ObjectId("57e66baba3e9070470605b9c"),
        "authors" : {
                "author_id" : "1",
                "name" : "**Update** - Chetan Bhagat"
        },
        "book_id" : "1",
        "title" : "**Updated** - One Indian Girl",
        "isbn" : "8129142147",
        "price" : "$18.00",
        "publish_date" : ISODate("2016-09-30T18:30:00Z")
}
{
        "_id" : ObjectId("57e66baba3e9070470605b9d"),
        "authors" : {
                "author_id" : "2",
                "name" : "Sarina Singh"
        },
        "book_id" : "2",
        "title" : "**Updated** - Book Title",
        "isbn" : "1743216769",
        "price" : "$34.99",
        "publish_date" : ISODate("2015-09-30T18:30:00Z")
}
{
        "_id" : ObjectId("57e66baba3e9070470605b9e"),
        "authors" : {
                "author_id" : "3",
                "name" : "John Keay"
        },
        "book_id" : "3",
        "title" : "**Updated** - Book Title",
        "isbn" : "0802145582",
        "price" : "$20.00",
        "publish_date" : ISODate("2011-03-31T18:30:00Z")
}
>


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0236 seconds.