0
如何從mongodb的內部文檔獲取字段?例如,如果我給一個名爲「idMovie」的字段,我會得到與此idMovie相對應的字段的其餘部分。從mongodb的內部文檔中的數組獲取值
我使用這個代碼:
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"
}]
}
預先感謝您! :) 對不起我的英語不好。
我試圖做到這一點,沒有成功:'如果(cursor.hasNext()){ \t \t \t \t \t \t \t \t DBOBJECT resultElement = cursor.next(); \t \t \t \t average =(String)resultElement.get(「average」); \t \t \t \t id =(String)resultElement.get(「idMovie」); \t \t \t \t sum =(String)resultElement.get(「sum」); \t \t \t \t numCal =(字符串)resultElement.get( 「總」);' – HCarrasko
你會需要這樣的東西: DBOBJECT resultElement = cursor.next(); 列表 list =(列表)resultElement.get(「rateMovies」); //遍歷這個列表來拉你的平均值 –
evanchooly
我會試試,謝謝! – HCarrasko