Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Mongodb query using $elemMatch in Java

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.

like image 987
Saurabh Avatar asked Aug 18 '26 05:08

Saurabh


1 Answers

elemMatch should be in find method not in projection bson. For example:

collection.find(elemMatch("statusLog", eq("status", "Submitted"))).projection(projection);
like image 143
Anuj Thakwani Avatar answered Aug 20 '26 19:08

Anuj Thakwani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!