从mongodb中的内部文档中的数组中获取值

时间:2014-03-13 15:30:43

标签: java mongodb mongodb-java nosql

如何从mongodb中的内部文档中获取字段?例如,如果我给出一个名为" idMovie"的字段,我将获得与此idMovie对应的其余字段。

我正在使用此代码:

        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();
        }
    }

当我运行它时,控制台会打印:

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

这是我正在使用的mongodb文档:

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

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

提前谢谢!! :)对不起我的英文。

1 个答案:

答案 0 :(得分:1)

您尝试从传入的查询对象中提取数据,而不是通过游标返回DBObject。