0

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.

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

You can add a new sub-document (or object) to an array using the following code. This uses the Updates builder class:

Document newPlayer = new Document("player", "tom").append("age", 22);
Bson update = Updates.push("game.team1", newPlayer);
Bson filter = Filters.eq("_id", new ObjectId("5e930d68618c45b052492407"));
UpdateResult result = collection.updateOne(filter, update);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.