Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB update using Java 3 driver

Tags:

mongodb-java

I'm switching to the MongoDB Java driver version 3. I cannot figure out how to perform an update of a Document. For example, I want to change the "age" of an user:

MongoDatabase db = mongoClient.getDatabase("exampledb");
MongoCollection<org.bson.Document> coll = db.getCollection("collusers");

Document doc1 = new Document("name", "frank").append("age", 55) .append("phone", "123-456-789");
Document doc2 = new Document("name", "frank").append("age", 33) .append("phone", "123-456-789");
coll.updateOne(doc1, doc2); 

The output is:

java.lang.IllegalArgumentException: Invalid BSON field name name

Any idea how to fix it ? Thanks!

like image 911
user2824073 Avatar asked Apr 03 '15 14:04

user2824073


People also ask

Does MongoDB have a JDBC driver?

Progress DataDirect's JDBC Driver for MongoDB offers a high-performing, secure and reliable connectivity solution for JDBC applications to access MongoDB data.


Video Answer


2 Answers

Use:

coll.updateOne(eq("name", "frank"), new Document("$set", new Document("age", 33)));

for updating the first Document found. For multiple updates:

coll.updateMany(eq("name", "frank"), new Document("$set", new Document("age", 33)));

On this link, you can fine a quick reference to MongoDB Java 3 Driver

like image 58
Francesco Marchioni Avatar answered Oct 21 '22 16:10

Francesco Marchioni


in Mongodb Java driver 3.0 , when you update a document, you can call the coll.replaceOne method to replace document, or call the coll.updateOne / coll.updateMany method to update document(s) by using $set/$setOnInsert/etc operators.

in your case, you can try:

coll.updateOne(eq("name", "frank"), new Document("$set", new Document("age", 33)));
coll.replaceOne(eq("name", "frank"), new Document("age", 33));
like image 38
Zhongqiang Pu Avatar answered Oct 21 '22 15:10

Zhongqiang Pu