Mongo collection named persons1 contains the following data:
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 }
Now through Java I have written the code to increment the count for the users which are present in the list
MongoClient mongocliet = new MongoClient("localhost", 27017);
MongoDatabase db=mongocliet.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));
After i run the above java program my output was as below.
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 }
My question is ,is it possible to Insert and start the count from 1 , for the entry present in the Array list and not present in the persons1 Collection.
Problem Description:
Before Program database contains details as follows:
{ "_id" : "Sims", "count" : 33 }
{ "_id" : "Autumn", "count" : 36 }
{ "_id" : "Becker", "count" : 35 }
{ "_id" : "Cecile", "count" : 40 }
{ "_id" : "Poole", "count" : 32 }
{ "_id" : "Nanette", "count" : 31 }
Sample Java code:
MongoClient mongocliet = new MongoClient("localhost", 27017);
MongoDatabase db=mongocliet.getDatabase("testdb1");
MongoCollection<Document> collection = db.getCollection("persons1");
List li =new ArrayList();
li.add("Sims"); //Entry already Present so required to increment by 1
li.add("Autumn");//Entry already Present so required to increment by 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");//Entry is NOT Present , Hence insert into persons data base with "_id" as User1 and count as 1
//Code to be written
What should be the code to get the out put from the db as shown below:
{ "_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
Is it possible to achieve the above stated requirement using mongo Java Driver