使用upsert在java中使用MongoDB获取com.mongodb.MongoException $ DuplicateKey [英] Getting com.mongodb.MongoException$DuplicateKey in mongodb with java using upsert
本文介绍了使用upsert在java中使用MongoDB获取com.mongodb.MongoException $ DuplicateKey的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法使用Java使用mongo db upsert更新现有记录. 我编写了一个查询,使用id查找记录,但是尝试更新其引发的com.mongodb.MongoException $ DuplicateKey异常.
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.
样本数据:
{"_id" : ObjectId("5788bef4191fda5c9077af78"),
"type" : "PRIVATE",
"users" : [
{
"_id" : "800",
"Name" : "Jack"
},
{
"_id" : "530a7998-ba3f-4366-8d21-bb1ca688cfdb",
"Name" : "Ashley"
}
]}
Java查询
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
推荐答案
我们只需要将列表传递给addToset即可.并设置为更新字符串字段.
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);
这篇关于使用upsert在java中使用MongoDB获取com.mongodb.MongoException $ DuplicateKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文