Search code examples
javamongodbchild-nodes

How to Query MongoDB Using Child Nodes in Java


I'm trying to query mongodb with java. The name of my collection is: reads. Here is an example of a specific document I'm querying for:

{
"_id" : {
    "d" : "B66929932",
    "r" : "15500304",
    "eT" : ISODate("2014-09-29T12:03:00Z")
},
"v" : 169000,
"iT" : ISODate("2015-04-10T20:42:07.577Z")

}

I'm trying to query where r = 15500304, eT = 2014-09-29T12:03:00Z and v = 169000. I'm able to do this in mongo pretty easily:

db.reads.find({ "_id.r" : "15500304", "_id.eT" : ISODate("2014-09-29T12:03:00Z"), "$where" : "this.v == 169000;"}).pretty()

I'm unable to figure out how to structure this in java. So far I've got:

DBCollection collection = db.getCollection("reads");
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();

obj.add(new BasicDBObject("_id.r", "15500304"));
obj.add(new BasicDBObject("_id.eT", "2014-09-29T12:03:00Z"));
obj.add(new BasicDBObject("v", 169000));
andQuery.put("$and", obj);

DBCursor cursor = collection.find(andQuery);
    while(cursor.hasNext()){
        System.out.println(cursor.next());
    }

My Question is: How do I query using these child nodes and return the matching document?

I'm unable to find any clear advice/examples online. Any and all advice is very appreciated.


Solution

  • You were close. Modify your query to:

    DBCollection collection = db.getCollection("reads");
    BasicDBObject query = new BasicDBObject();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    String dateInString = "2014-09-29T12:03:00Z";
    Date date = df.parse(dateInString);
    
    query.append("status.name", "Expired")
         .append("_id.eT", date)
         .append("v", 169000);
    

    Or using QueryBuilder:

    DBObject query = QueryBuilder.start()
                             .put("_id.r").is("15500304")
                             .put("_id.eT").is(date)
                             .put("v").is(169000)
                             .get();
    
    DBCursor cursor = collection.find(query);
    while(cursor.hasNext()){
        System.out.println(cursor.next());
    }