我正在尝试使用Java驱动程序查询mongodb数据库中另一个文档中另一个文档中是否存在字段。我要求的字段是idMovie。
例如,如果idMovie为2,我希望它在控制台中显示“ idMovie值已经存在”。或如果idMovie为10,则打印“不存在”,因为文档中没有10
这是我的bson对象:
{ "_id" : { "$oid" : "5320aa3c3e468eaeb52dccdc"},
"document" : "movies" ,
"rateMovies" : [
{
"idMovie" : 2 ,
"average" : "0" ,
"sum" : "0" ,
"total" : "0"
} ,
{
"idMovie" : 3 ,
"average" : "0" ,
"sum" : "0" ,
"total" : "0"
}]
}
这是我的Java代码:
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");
}
,但不适用于我。任何帮助都很好,谢谢!!
最佳答案
感谢您的帮助,但我自己找到了答案。
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);