问题
I am not able to update the existing record with mongo db upsert using java. I wrote a query to find the record using id but when trying to update its throwing com.mongodb.MongoException$DuplicateKey exception.
Sample data:
{"_id" : ObjectId("5788bef4191fda5c9077af78"),
"type" : "PRIVATE",
"users" : [
{
"_id" : "800",
"Name" : "Jack"
},
{
"_id" : "530a7998-ba3f-4366-8d21-bb1ca688cfdb",
"Name" : "Ashley"
}
]}
Java query
Query query = new Query();
query.addCriteria(Criteria.where("_id").is("5788bef4191fda5c9077af78"));
Update args = new Update();
args.addToSet("users", users);// users is a List<User>users.
args.addToSet("type", "GROUP");
mongoOps.upsert(query, args, Rooms.class, ROOMS);//mongoOps is MongoOperations
回答1:
We need to pass only list to addToset . And set to update a string field.
Below code worked and document got updated.
Update args = new Update(); args.addToSet("users", new BasicDBObject("$each", users)); args.set("type", "GROUP"); mongoOps.upsert(query, args, Rooms.class, ROOMS);
来源:https://stackoverflow.com/questions/38395261/getting-com-mongodb-mongoexceptionduplicatekey-in-mongodb-with-java-using-upser