I'm using java and mongodb v.3.0.7. I have a list of player with internal array of games with scores. This is a test that insert a document:
public void insertPlayer(String id_device) throws ParseException{
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
db.getCollection("player").insertOne(
new Document()
.append("nikname", "Guest")
.append("password", "Guest")
.append("my_id", "")
.append("id_device", id_device)
.append("language", "Italian")
.append("games", asList(
new Document()
.append("gamename", "PPA")
.append("banned", false)
.append("date", format.parse("2014-10-01T00:00:00Z"))
.append("score", 11),
new Document()
.append("gamename", "Test2game")
.append("banned", false)
.append("date", format.parse("2014-01-16T00:00:00Z"))
.append("score", 17)))
);
}
To find if a player is banned from a particular game I'm doiing this:
public boolean isBanned(String id_device){
FindIterable<Document> iterable = db.getCollection("player").find(eq("id_device", "machine1"));
System.out.println(iterable.first());
List<Document> dl = (List<Document>)iterable.first().get("games");
for(int i=0;i<dl.size();i++){
Document d = dl.get(i);
System.out.println(d.getString("gamename"));
if(d.getString("gamename").equals("PPA")){
boolean ban = d.getBoolean("banned");
return ban;
}
}
There is a faster way using embedded mongodb methods that find the document:
new Document()
.append("gamename", "PPA")
.append("banned", false)
.append("date", format.parse("2014-10-01T00:00:00Z"))
.append("score", 11),
giving id_device and gamename? thanks