简体   繁体   中英

How to query mongodb with 'equality' in java

I have following BSON in Mongodb

{
    "_id" : ObjectId("52a30bdfaaa83ba83c25c0f3"),
    "course" : {
        "course_name" : "Java EE",
        "description" : "Java Enterprise Edition"
    },
    "first_name" : "Lucy",
    "last_name" : "Hill",
    "gender" : "female"
}

I want to find all the document which has "course_name" = "Java EE". In java, I had tried this code but it didn't seem to be working.

DBCollection table = db.getCollection("Students"); //my Collection
BasicDBObject courseNameDBObject = new BasicDBObject() 
            .append("course", new BasicDBObject("course_name", "Java EE"));
DBCursor cursor = table.find(courseNameDBObject);
while(cursor.hasNext()){
    System.out.println(cursor.next());
}

Could anyone help me?

DBCollection table = db.getCollection("Students"); //my Collection
BasicDBObject courseNameDBObject = new BasicDBObject("course.course_name", "Java EE") ;
DBCursor cursor = table.find(courseNameDBObject);
while(cursor.hasNext()){
    System.out.println(cursor.next());
}

You can use . to access fields within a sub document.

Official documentation on querying

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM