This tutorial shows how to update documents in the collection in MongoDB using a Java program.
The MongoCollection's updateOne() method is used to update a document.
The MongoCollection's updateOne() method is used to update a document.
MongoDB is a cross-platform, document-oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on the concept of collection and document.
Learn MongoDB with Java at https://www.javaguides.net/p/java-mongodb-tutorial.html
Tools and Technologies Used
- Java (JDK) 10
- Maven 3.5+
- Eclipse Neon
- MongoDB 3.12.0
Installing MongoDB
Use the following article to install MongoDB on Windows 10.
Make sure that you have installed MongoDB and started MongoDB server on default port 27017.
Database Setup
In the previous tutorial, we have created MongoDB database, collection and inserts few documents into a collection.
Java MongoDB Driver
We use the following Maven declaration to include the MongoDB Java Driver in our maven project.
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.0</version>
</dependency>
Note that it is an all-in-one JAR, which embeds the core driver and BSON. BSON, short for Binary JSON, is a binary-encoded serialization of JSON-like documents.
Java MongoDB Update Document Example - updateOne() Method
In the following example, we are updating lastName of the user "Ramesh":
package net.javaguides.mongodb.document;
import java.util.ArrayList;
import org.bson.Document;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoUpdateDocument {
public static void main(String[] args) {
// Creating a Mongo client
try (var mongoClient = MongoClients.create("mongodb://localhost:27017")) {
// Accessing the database
MongoDatabase database = mongoClient.getDatabase("javaguides");
// Retieving a collection
MongoCollection < Document > collection = database.getCollection("users");
collection.updateOne(new Document("_firstName", "Ramesh"),
new Document("$set", new Document("_lastName", "Pawar")));
// Retrieving the documents after updation
try (MongoCursor < Document > cur = collection.find().iterator()) {
while (cur.hasNext()) {
var doc = cur.next();
var users = new ArrayList < > (doc.values());
System.out.printf("%s: %s%n", users.get(1), users.get(2));
}
}
}
}
}
Output:
Tony: Stark
Tom: Cruise
Amir: Khan
Umesh: Fadatare
Ramesh: Pawar
Note that the lastName of "Ramesh" is changed to "Pawar" with the updateOne() method.
collection.updateOne(new Document("_firstName", "Ramesh"),
new Document("$set", new Document("_lastName", "Pawar")));
Java MongoDB Tutorials
All Java MongoDB tutorials at https://www.javaguides.net/p/java-mongodb-tutorial.html
Comments
Post a Comment
Leave Comment