【发布时间】:2015-11-30 14:50:19
【问题描述】:
名为 people1 的 Mongo 集合包含以下数据:
db.persons1.find().pretty();
{ "_id" : "Sims", "count" : 32 }
{ "_id" : "Autumn", "count" : 35 }
{ "_id" : "Becker", "count" : 35 }
{ "_id" : "Cecile", "count" : 40 }
{ "_id" : "Poole", "count" : 32 }
{ "_id" : "Nanette", "count" : 31 }
现在通过 Java,我编写了代码来增加列表中存在的用户的计数
MongoClient mongoclient = new MongoClient("localhost", 27017);
MongoDatabase db = mongoclient.getDatabase("testdb1");
MongoCollection<Document> collection = db.getCollection("persons1");
List li = new ArrayList();
li.add("Sims");
li.add("Autumn");
collection.updateMany(
in("_id",li),
new Document("$inc", new Document("count", 1)),
new UpdateOptions().upsert(true));
运行上面的java程序后,我的输出如下。
db.persons1.find().pretty();
{ "_id" : "Sims", "count" : 33 }
{ "_id" : "Autumn", "count" : 36 }
{ "_id" : "Becker", "count" : 35 }
{ "_id" : "Cecile", "count" : 40 }
{ "_id" : "Poole", "count" : 32 }
{ "_id" : "Nanette", "count" : 31 }
我的问题:是否可以插入并从 1 开始计数,用于 Array 列表中存在的条目而不存在于 person1 集合中?
问题描述:
之前的程序数据库包含以下详细信息:
{ "_id" : "Sims", "count" : 33 }
{ "_id" : "Autumn", "count" : 36 }
{ "_id" : "Becker", "count" : 35 }
{ "_id" : "Cecile", "count" : 40 }
{ "_id" : "Poole", "count" : 32 }
{ "_id" : "Nanette", "count" : 31 }
示例 Java 代码:
MongoClient mongoclient = new MongoClient("localhost", 27017);
MongoDatabase db = mongoclient.getDatabase("testdb1");
MongoCollection<Document> collection = db.getCollection("persons1");
List li = new ArrayList();
// Entry already Present so required to increment by 1
li.add("Sims");
// Entry already Present so required to increment by 1
li.add("Autumn");
// Entry is NOT Present, hence insert into persons data base with "_id" as User1 and count as 1
li.add("User1");
// Entry is NOT Present, hence insert into persons data base with "_id" as User1 and count as 1
li.add("User2");
// Code to be written
从数据库中获取输出的代码应该是什么,如下所示:
{ "_id" : "Sims", "count" : 34 } // Entry already Present, incremented by 1
{ "_id" : "Autumn", "count" : 37 } // Entry already Present, incremented by 1
{ "_id" : "Becker", "count" : 35 }
{ "_id" : "Cecile", "count" : 40 }
{ "_id" : "Poole", "count" : 32 }
{ "_id" : "Nanette", "count" : 31 }
{ "_id" : "User1", "count" : 1 } // Entry Not Present, start by 1
{ "_id" : "User2", "count" : 1 } // Entry Not Present, start by 1
【问题讨论】:
-
据我所见,您建议的代码应该正确执行。那么结果中什么对您不起作用?
-
我的代码不会插入新的 id,作为更新的一部分,我只包括增量运算符..如何包含 id 的列表。所以如果它在 arraylist 中找不到 id,它将插入计数作为一个,但 id 是从 mongo db 内部生成的。
-
这不可能是真的。 1.
_id是“必填项”,必须始终插入。 2.您确实提供了一个列表和.updateMany()方法“包装”以暗示“多”作为参数。以及你有“upsert”。如果您认为自己有不同,请显示结果以使其成为可重复的案例。 -
collection.updateMany(in("_id",li), new Document("$inc", new Document("count", 1).append("$set", new Document(" _id", li)))) , new UpdateOptions().upsert(true));
-
代码应该如上吗?
标签: java mongodb mongodb-query mongodb-java