[JAVA-2288] updateOne semantic is not as expected Created: 24/Aug/16  Updated: 11/Sep/19  Resolved: 04/Nov/16

Status: Closed
Project: Java Driver
Component/s: API
Affects Version/s: 3.2.0
Fix Version/s: None

Type: Task Priority: Major - P3
Reporter: Stephan Frind Assignee: Unassigned
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

The first way to perform an update to a document would be (from my point of view) something like this

   Document tempDoc = new Document();
   tempDoc.put("value", "new value");
   collection.updateOne(Filters.eq("_id", 1), tempDoc);

but this leads to

Exception in thread "main" java.lang.IllegalArgumentException: Invalid BSON field name value

I have to wrap my update in another document

Document tempDoc = new Document();
    tempDoc.put("value", "new value");
    Document tempUpdateOp = new Document("$set", tempDoc);
    collection.updateOne(Filters.eq("_id", 1), tempUpdateOp);

This is strange because there is no need to wrap it. For the purpose of replacing a document there is another method replaceOne. Why do I have to wrap my update into another document for the updateOne call?



 Comments   
Comment by Jeffrey Yemin [ 04/Nov/16 ]

It works this way because update supports more than just $set. See https://docs.mongodb.com/v3.2/reference/operator/update/ for the full list.

It looks like what you'd like is for updateOne/updateMany to assume a $set if the document doesn't contain any $-prefixed keys. That makes sense as a shortcut for a common idiom, but others may prefer a helper that assumes $inc instead, or some other update operator. Rather than provide MongoCollection helpers for these idioms, the driver instead provides the Updates class, so you can do:

collection.updateOne(Filters.eq("_id", 1), Updates.set('x', 5));

You can statically import eq and set for even more brevity.

Hope this will satisfy your needs.

Generated at Thu Feb 08 08:56:50 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.