我正在尝试使用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");
}
,但不适合我。任何帮助都很好,谢谢!!
答案 0 :(得分:1)
谢谢你的帮助,但我自己找到答案。
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);
答案 1 :(得分:0)
试试这个:
searchQuery.put("idMovie", new BasicDBObject("$exists",true));