Search code examples
javamongodbmongodb-java

Push new object into an array of an existing document using MongoDB Java


I am trying to learn MongoDB and would like to know how I can insert POJO into existing collection. My collection looks exactly as below.

{
        "_id" : ObjectId("5e930d68618c45b052492407"),
        "game" : {
                "team1" : [ 
                    { "player" : "john", "age" : 25 },
                    { "player" : "mick", "age" : 25 }
                ],

                "team2" : [ 
                    { "player" : "john", "age" : 25 },
                    { "player" : "john", "age" : 25 }
                ]
            }
}

Now I want to be able to insert a new player inside "team1" and the expected output should like the below,

{
        "_id" : ObjectId("5e930d68618c45b052492407"),
        "game" : {
                "team1" : [ 
                    { "player" : "john", "age" : 25 },
                    { "player" : "mick", "age" : 23 },
                    { "player" : "tom", "age" : 22 }   //newly inserted
                ],

                "team2" : [ 
                    { "player" : "tony", "age" : 26 },
                    { "player" : "bruce", "age" : 24 }
                ]
            }
}

I have used POJO in java and my code is below,

Player object= new Player();
newPlayer.setPlayer("tom");
newPlayer.setAge(22);

BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$push", object);

collection.updateOne(Filters.and(Filters.eq("_id", "5e930d68618c45b052492407"), Filters.eq("game.team1")), setQuery);

But the above seems not works and request to help me on this. Please excuse me if you find any mistakes on my question.Thanks in advance.


Solution

  • ok I have found solution by myself, for those who ended up here with same problem, here is the solution that I have found.

    BasicDBObject query = new BasicDBObject();
    query.put("_id", valueofId);
    
    BasicDBObject push_data = new BasicDBObject("$push", new BasicDBObject("game.team1", object));
    
    collection.findOneAndUpdate(query, push_data);