蒙戈集合包含以下數據:
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」。如果你認爲你有不同的話,請展示結果,以使其成爲一個可重現的案例。 –