Question

I'm trying ask if a field exist inside a document inside another document in an mongodb database using java driver. The field that I asking for is idMovie.

For example, I expect that it print in the console "idMovie value already exist" if idMovie is 2, for example. Or print "not exist" if idMovie is 10, because 10 are not in the document

this is my bson object:

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

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

And this is my java code:

MongoClient mongo = new MongoClient ("localhost", 27017);
        DB db = mongo.getDB("DBHC2");
        DBCollection movieDocument = db.getCollection("rateMovies");

        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("idMovie", idMovie);
        DBCursor cursor = movieDocument.find(searchQuery);

        /* if is true, the idMovie value already exist in database. */
        if(cursor.hasNext()){
            System.out.println("idMovie value already exist");
        }
        else{
            System.out.println("not exist");
        }

, but don't works for my. Any help is good received, thank you!!

Was it helpful?

Solution

Thanks for you help, but I find the answer by my self.

        MongoClient mongo = new MongoClient ("localhost", 27017);
        DB db = mongo.getDB("DBHC2");
        DBCollection movieDocument = db.getCollection("movies");

        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("rateMovies.idMovie", idMovie);
        DBCursor cursor = movieDocument.find(searchQuery);

OTHER TIPS

Try this:

    searchQuery.put("idMovie", new BasicDBObject("$exists",true));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top