I am using Mongo java driver to retrieve data from mongo collections. I have the following query which I am trying to implement in java: Json is:
{
"_id" : ObjectId("56cd284767c74d3d4dd3ec80"),
"comments" : "Hello",
"statusLog" : [
{
"status" : "Submitted",
"startDate" : ISODate("2015-01-14T05:00:00.000Z"),
"endDate" : ISODate("2016-02-29T21:24:24.740Z")
},
{
"status" : "Active",
"startDate" : ISODate("2016-02-29T21:24:24.740Z")
}
],
"createdDate" : ISODate("2015-01-14T05:00:00.000Z")
}
Mongo Query:
db.CollectionName.find({},{_id: 0, createdDate:1, "statusLog": {$elemMatch: {"status":"Submitted"}}});
Here is the query in java that I have written (mongo java driver 3.4.2):
BasicDBObject query = new BasicDBObject(new BasicDBObject("statusLog",
new BasicDBObject("$elemMatch", new BasicDBObject("status", "Submitted"))));
Running the java code returns all status logs and not the one that I am looking for.
Any help would be highly appreciated.
elemMatch
should be in find method not in projection bson. For example:
collection.find(elemMatch("statusLog", eq("status", "Submitted"))).projection(projection);