Question

how can I get a field from a inner document in mongodb?? For example if I give a field called "idMovie", I would get the rest of field that correspond to this idMovie.

I'm using this code:

        MongoClient mongo = null;
        DBCursor cursor = null;
        String average = "";
        String sum = "";
        String numCal = "";

        try {
            mongo = new MongoClient ("localhost", 27017);
            DB db = mongo.getDB("DBHC2");

            DBCollection movieDocument = db.getCollection("movies");
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("rateMovies.idMovie", idMovie);
            cursor = movieDocument.find(searchQuery);

            if(cursor.hasNext()){

                average = searchQuery.getString("average");
                sum     = searchQuery.getString("sum");
                numCal  = searchQuery.getString("total");

                System.out.println("***** Debug: average: "+average+" sum: "+sum+" total: "+numCal);    
            }           
        }
        catch(Exception e){ 
            System.out.println("error : " + e.getMessage());
            System.out.println("error : " + e.getCause());
        }
        finally{
            cursor.close();
        }
    }

When I run it, the console prints:

***** Debug: average: null sum: null total: null

this is the mongodb document that I'm using:

{ "_id" : { "$oid" : "5320aa3c3e468eaeb52dccdc"}, 
   "document" : "movies" , 
   "rateMovies" : [ 
        { 
         "idMovie" : 2 , 
         "average" : "0" , 
         "sum" : "0" , 
         "total" : "0"
        } , 

       { 
         "idMovie" : 3 ,
         "average" : "0" ,
         "sum" : "0" , 
         "total" : "0"
       }]
  } 

Thank you in advance!! :) sorry for my english.

Was it helpful?

Solution

You're trying to extract data from the query object you pass in rather than the DBObjects return via the cursor.

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