New CS Developer
New CS Developer

Reputation: 29

Java Program to add an array to an existing object in mongoDB

I am creating a program that allows a user to insert a team, the size of the team and player data. The code works, but not in the way that I want it to. I want the program to add an array of "players" and to add data to the database for each player in the array according to team size. So if a user inputs 2 team players, there are 2 objects in the array "players". My program only records only one team player and I'm not sure how to record all of the team players in an array for my database. My code is below:

addTeamPlayer()

public static Document addTeamPlayer() throws IOException {
    MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
    MongoDatabase db = mongoClient.getDatabase("teamDB");
    MongoCollection<Document> col = db.getCollection("teamCollection");
        
    BufferedReader bfn = new BufferedReader(new InputStreamReader(System.in));
        
    Random rand = new Random();
    int rand_int = rand.nextInt(25);

    System.out.println("Player name: ");
    String playerInput = bfn.readLine();
        
    System.out.println("Age: ");
    int ageInput = Integer.parseInt(bfn.readLine());
        
    System.out.println("Position: ");
    String positionInput = bfn.readLine();
        
    System.out.println("Ranking: ");
    int rankingInput = Integer.parseInt(bfn.readLine());
        
    Document playerDoc = new Document("player_id", Integer.toString(rand_int));
    playerDoc.append("player_name", playerInput)
        .append("age", ageInput)
        .append("position", positionInput)
        .append("ranking", rankingInput);
        
    //col.insertOne(playerDoc);
        
    return playerDoc;
}

addTeam()

    public static Document addTeam() throws IOException {
        
        MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
        MongoDatabase db = mongoClient.getDatabase("teamDB");
        MongoCollection<Document> col = db.getCollection("teamCollection");
        
        BufferedReader bfn = new BufferedReader(new InputStreamReader(System.in));
        
        Random rand = new Random();
        int rand_int = rand.nextInt(25);
        
        System.out.println("Team name: ");
        String teamInput = bfn.readLine();
        System.out.println("How many players: ");
        int teamSize = Integer.parseInt(bfn.readLine());
        
        Document teamDoc = new Document("_id", new ObjectId());
        System.out.println("Team name: ");
        teamDoc.append("team_id", Integer.toString(rand_int))
            .append("team_name", teamInput).toString();
        
        for(int i = 1; i <= teamSize; i++) {
            System.out.println("Player " + i + "--");
            teamDoc.append("players", addTeamPlayer());
        }
        
        col.insertOne(teamDoc);
        
        return teamDoc;
    }

JSON Expected Output

{
      "_id": {
        "$oid": "62cde01f3e99574b06e59d19"
      },
      "team_id": "11",
      "team_name": "Seahawks",
      "players": [
        {
        "player_id": "0",
        "player_name": "Joe Brown",
        "age": 23,
        "position": "Tight End",
        "ranking": 5
        },
        {
        "player_id": "0",
        "player_name": "Joe Brown",
        "age": 23,
        "position": "Tight End",
        "ranking": 5
        }
      ]
}

Upvotes: 0

Views: 33

Answers (1)

barrypicker
barrypicker

Reputation: 10088

I think you want to update an existing record, right? I mean, you have a teamCollection record but without any players, and you want to add players to an existing team's record, correct? If so, how about this?

addTeamPlayer()

public static Document addTeamPlayer() throws IOException {
    MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
    MongoDatabase db = mongoClient.getDatabase("teamDB");
    MongoCollection<Document> col = db.getCollection("teamCollection");
        
    BufferedReader bfn = new BufferedReader(new InputStreamReader(System.in));
        
    Random rand = new Random();
    int rand_int = rand.nextInt(25);

    System.out.println("Player name: ");
    String playerInput = bfn.readLine();
        
    System.out.println("Age: ");
    int ageInput = Integer.parseInt(bfn.readLine());
        
    System.out.println("Position: ");
    String positionInput = bfn.readLine();
        
    System.out.println("Ranking: ");
    int rankingInput = Integer.parseInt(bfn.readLine());
        
    Document playerDoc = new Document("player_id", Integer.toString(rand_int));
    playerDoc.append("player_name", playerInput)
        .append("age", ageInput)
        .append("position", positionInput)
        .append("ranking", rankingInput);
        
    org.bson.conversions.Bson filter = new org.bson.Document(); //com.mongodb.client.model.Filters.eq("_id", 1);
    org.bson.conversions.Bson update = com.mongodb.client.model.Updates.push("players", playerDoc);

    com.mongodb.client.model.FindOneAndUpdateOptions options = new com.mongodb.client.model.FindOneAndUpdateOptions().returnDocument(com.mongodb.client.model.ReturnDocument.AFTER);
    org.bson.Document result = col.findOneAndUpdate(filter, update, options);
    System.out.println(result.toJson());
        
    return playerDoc;
}

Explanation

The strategy is to use the push operator. This is an array based operator. It's use signifies the database should append to an array.

In my example the find filter is empty (simply a new document). This will find and update any arbitrary record. If you want to update a specific record you can add a filter to specify. I have included (but commented out) the code to specify a filter.

See MongoDB documentation online at https://www.mongodb.com/docs/drivers/java/sync/current/fundamentals/crud/write-operations/embedded-arrays/

I could imaging you have a parameter in the method addTeamPlayer that is the id of the record you wish to update. If so, you could create a filter and find the specific team to append a player to.

Upvotes: 1

Related Questions