Java & MongoDB - Update Document


Advertisements

To update a document in a collection, you can use collection.updateOne() method to update a particular document of a collection.

collection.updateOne(filter,update);

Example

Following is the code snippet to update and display updated document −

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;

public class Tester {
   public static void main(String[] args) {
      // Creating a Mongo client 
      MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
      MongoDatabase database = mongoClient.getDatabase("myDb");

      // Get the collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");

      // Find all documents
      collection.updateOne(Filters.eq("First_Name","Mahesh"),
      Updates.set("e_mail", "maheshparashar@gmail.com"));
      System.out.println("Document Updated.");
      System.out.println("***Updated Document***");
      
      // Select a particular document
      FindIterable<Document> documents = collection.find(Filters.eq("First_Name","Mahesh"));

      for (Document document : documents) {
         System.out.println(document);
      }
   }
}

Now, let's compile and run the above program as shown below.

$javac Tester.java 
$java Tester

Output

On executing, the above program gives you the following output.

Document Updated.
***Updated Document***
Document{{_id=60b70d426214461f10ac5c99, First_Name=Mahesh, Last_Name=Parashar, Date_Of_Birth=1990-08-21, e_mail=maheshparashar@gmail.com, phone=9034343345}}

Useful Video Courses


Video

Java Date and Time Online Training

16 Lectures 2 hours

Malhar Lathkar

Video

Java Servlet Online Training

19 Lectures 5 hours

Malhar Lathkar

Video

JavaScript Online Training

25 Lectures 2.5 hours

Anadi Sharma

Video

Java Online Training

Most Popular

126 Lectures 7 hours

Tushar Kale

Video

Java Essential Training

119 Lectures 17.5 hours

Monica Mittal

Video

Java Essentials Online Training

76 Lectures 7 hours

Arnab Chakraborty

Advertisements