0

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");
kunal18
  • 1,935
  • 5
  • 33
  • 58

1 Answers1

0

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
}
assylias
  • 321,522
  • 82
  • 660
  • 783
  • I have tried it. But it does not work for me! Have you tried it? Did you got the result? – kunal18 Jun 27 '13 at 14:39
  • @stalin Are you sure there is no typo in `address.street` and in `123 Main Street` when you create the DBObject? Yes I just tried it with you data and it worked. – assylias Jun 27 '13 at 14:40
  • @stalin Just to be sure, could it be that you are trying with `new BasicDBObject("address.street", "123")` instead of `new BasicDBObject("address.street", "123 Main Street")`? – assylias Jun 27 '13 at 14:41
  • Thanks! It worked. I was making some mistake. "address.street" is correct. – kunal18 Jun 27 '13 at 14:53