Implementing Mongodb query using $elemMatch in Java

Saurabh picture Saurabh · May 19, 2017 · Viewed 7.4k times · Source

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.

Answer

s7vr picture s7vr · May 19, 2017

You should use newer Document/MongoCollection api and use helper methods to prepare projection.

import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Projections.*;

MongoClient mongoClient = new MongoClient(); 
MongoDatabase database = mongoClient.getDatabase("db"); // Get DB

MongoCollection<Document> collection = database.getCollection("collection"); // Get Collection
Bson projection = Projections.fields( excludeId(), include("createdDate"), elemMatch("statusLog", eq("status", "Submitted"))); // Add Projections
FindIterable<Document> iterable = collection.find().projection(projection);

Using old BasicDBObject/DBCollection api

MongoClient mongoClient = new MongoClient();
DB database = mongoClient.getDB("db");

DBCollection collection = database.getCollection("collection");
BasicDBObject projection = new BasicDBObject(new BasicDBObject("statusLog",new BasicDBObject("$elemMatch", new BasicDBObject("status", "Submitted"))));
collection.find(new BasicDBObject(), projection);