蒙戈集合包含以下数据:
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开始计数,对于存在于数组列表和persons1集合不存在的项目吗?
问题描述:
之前计划数据库包含详情如下:
{ "_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,它会插入count作为一个,但id是从mongo db内部生成。 –
这不可能是真的。 1.'_id'是“强制性的”,并且必须始终插入。 2.你提供了一个列表,'.updateMany()'方法“包装”以将“multi”作为参数。以及你有“upsert”。如果你认为你有不同的话,请展示结果,以使其成为一个可重现的案例。 –