Search code examples
mongodbmongodb-querymongodb-java

mongodb queries in Java


I am new to mongodb, I have a JSON like this:

{
    "first_name" : "John",
    "last_name"  : "Smith",
    "address" : {
        "street" : "123 Main Street",
        "city"   : "Anytown",
        "state"  : "NY"
   }
}

Now I want to find all documents where "street" = "123" (say). In mongo shell, I do it as follows:

db.collection_name.find(
  {
    'address.street' : '123'
  }
)

In Java if I want to find documents where "firstname" = "John", I do it as:

BasicDBObject nameQuery = new BasicDBObject();
nameQuery.put("firstname", "John");
DBCursor cursor = collection.find(nameQuery);

I cannot figure out for adress.street, I have tried something but it didn't work.

I tried this:

addressQuery.put("address.street", "123");

Solution

  • What you suggest should work. This works for me:

    DBCollection coll = db.getCollection(...);
    DBCursor cursor = coll.find(new BasicDBObject("address.street", "123 Main Street"));
    while (cursor.hasNext()) {
        System.out.println(cursor.next()); //prints the object
    }