Getting com.mongodb.MongoException$DuplicateKey in mongodb with java using upsert

邮差的信 提交于 2019-12-11 05:09:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!