0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I'm trying to do this, without success: if(cursor.hasNext()){ DBObject resultElement = cursor.next(); average = (String) resultElement.get("average"); id = (String) resultElement.get("idMovie"); sum = (String) resultElement.get("sum"); numCal = (String) resultElement.get("total");
You would need something like: DBObject resultElement = cursor.next(); List<DBObject> list = (List<DBObject>)resultElement.get("rateMovies"); // iterate over this list to pull your averages

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.