Hello all am working on mongodb with java, i have a scenario where if the outer document is matched then i have to update/add count in an nested array for eg i want to do something like this :
`"_id" : ObjectId("55d71603aed7562284e5df95"),
"id" : "1",
"type" : "a",
"score" : {
"mark1" : "1",
"mark2" : "2",
"count" : { "one","two"
}
}`
if again i send a document with same fields like id:1, type:a,mark1:1,mark2:2 then i have to get my document as
`"_id" : ObjectId("55d71603aed7562284e5df95"),
"id" : "1",
"type" : "a",
"score" : {
"mark1" : "1",
"mark2" : "2",
"count" : { "one","two","three"
}
}`
But i am getting some thing like this :
`"_id" : ObjectId("55d71e42aed7560e8c9d02e4"),
"id" : "1",
"type" : "a",
"score" : {
"mark1" : "1",
"mark2" : "2",
"count" : {
"count" : "one",
}
}`
My java code is
`mongoDatabase=mongoClient.getDatabase("TestNestedInsert");
Document sourceDocument=mongoDatabase.getCollection("entity").find(new Document("id",1).append("score.mark1", "1").append("score.mark2", "2")).first();
if(sourceDocument==null){
Document entity=new Document();
entity.append("id", "1");
entity.append("type", "a");
entity.append("score", new Document("mark1","1").append("mark2", "2").append("count", new Document("count","one")));
mongoDatabase.getCollection("entity").insertOne(entity);
}
else{
mongoDatabase.getCollection("entity").findOneAndUpdate(new Document("id",1).append("score.mark1", "1").append("score.mark2", "2"), new Document("$set",new Document("score.count","three")));
}
`
i know we cannot have duplicate keys i tried $set and $push as well but i am stuck. Any help ?