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
}
]
}
com.mongodb.client.model.Updates.pushEachto add aList<Document>(array of players) to team document in an update operation.