Question

Mongodb and JSP :

my code :


DBCursor curseur = table.find();

while (curseur.hasNext()) { 
    DBObject ligne = curseur.next();

    out.println(ligne.get("_id")); 
    out.println(ligne.get("joueur")); 
    out.println(ligne.get("equipes"));
    out.println(ligne.get("matchs"));
}

the code runs normally but the problem is in the display :


_id 1  
Joueur  { "nom" : "De Oliveira" , "prenom" : "Denilson"}  
Equipes [ "Sao Paulo FC" , "Bétis Seville" , "Bordeaux"]  
Matchs  [{ "date_m" : "1996" , "stade" : "Morumbi"}, 
         { "date_m" : "1999" , "stade" : "Benito Villamarn"}, 
         { "date_m" : "2005" , "stade" : "Chaban-Delmas"}]  

It's correct but :

  1. How can I know the number of columns?

  2. How can I access the sub documents?

I want to display a list of data with this structure (without the braces and brackets):


id : 1

Joueur : nom : De Oliveira
        prenom : Denilson

Equipes : Sao Paulo FC, Betis Seville, Bordeaux

matchs : date_m : 1996
         stade : Morumbi

         date_m : 1999
         stade : Benito Villamarn

         date_m : 2005
         stade : Chaban-Delmas

Thank you in advance for your cooperation !

Was it helpful?

Solution

If you want fetch the data inside an inner array of your document you need store it in a ArrayList or List of java, like this:

cursor = document.find(query);
     if(cursor.hasNext()) {
     ArrayList<?> Matchs = (BasicDBList) cursor.next().get("Matchs");
             /* here you can iterate over Matchs arrayList and get his data */
             for(int i=0; i< Matchs.size(); i++){
                   JsonParser jsonParser = new JsonParser();
                   JsonElement jsonElement = jsonParser.parse(String.valueOf(Matchs.get(i)));

                if (jsonElement.isJsonObject()) {
                   JsonObject jsonObject = jsonElement.getAsJsonObject();
                   String date_m = jsonObject.get("date_m").getAsString();
                   String stade = jsonObject.get("stade").getAsString();
                }
             }
     }

NOTE: You need add to you project a jar of google.gson, to deserialize more easily your bson object

https://code.google.com/p/google-gson/downloads/detail?name=google-gson-2.2.4-release.zip

I hope it helps.

OTHER TIPS

The number of "columns" can fetched using dbObject.size(). Subdocuments are just fields backed by other DBObjects so you fetch them the same way as any other field.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top