[JAVA-1340] DBCollection.save(DBObject jo) method adds new document even if the same _id already exists Created: 01/Aug/14  Updated: 03/Aug/14  Resolved: 03/Aug/14

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

Type: Bug Priority: Major - P3
Reporter: deepak vohra Assignee: Unassigned
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Windows 7
MongoDB 2.4.9
MongoDB Java Driver 2.11.3



 Description   

The save method adds another document with the same _id, for example 53dc0bf6c9d224c98f743a4e.



 Comments   
Comment by Jeffrey Yemin [ 03/Aug/14 ]

Oh, I see. You're using the String value of the ObjectId in rowUpdate. Try:

        rowUpdate.put("_id", new ObjectId("53dc0bf6c9d224c98f743a4e"));

instead.

Comment by deepak vohra [ 02/Aug/14 ]

//Add a row.
DBObject row1 = new BasicDBObject("col1", "val1").append("col2", "val2");
coll.insert(row);

//Obtain _id from the array output
row1 = coll.findOne();
System.out.println(row1); //for example _id is 53dc0bf6c9d224c98f743a4e

//Query row to update
BasicDBObject dbObjectUpdate = new BasicDBObject();
dbObjectUpdate.put("col1", "val1");
dbObjectUpdate.put("col2", "val2");
DBObject rowUpdate = coll.findOne(dbObjectUpdate);//The row with _id 53dc0bf6c9d224c98f743a4e gets fetched

//Set updated values for col1 and col2
rowUpdate.put("_id", "53dc0bf6c9d224c98f743a4e");
rowUpdate.put("col1", "val1_Updated");
rowUpdate.put("col2","val2_Updated");

//Save updated row
coll.save(rowUpdate);
//new document with _id 53dc0bf6c9d224c98f743a4e gets added even though same _id exists

Comment by Jeffrey Yemin [ 02/Aug/14 ]

Hi Deepak,

I'm not at all sure what you mean, as _id is unique within a MongoDB collection. Can you provide an example that shows exactly what you're seeing.

Regards,
Jeff

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