Search code examples
javamongodbquery-optimizationmongodb-querycrud

How to query only the specific fields in MongoDB with Java?


I'm using MongoDB 3.2 and MongoDB Java Driver 3.2. In order to query document I use the following code:

Document query = new Document("fetchStatus", new Document("$lte", fetchStatusParam));
ArrayList<Document> unfetchedEvents = dbC_Events.find(query).into(new ArrayList<Document>());

This query works but the problem is that in this case all fields of the document are retrieved (analog of select * in SQL). In order to optimize query performance, I want to specify fields I really need and fetch only them.

I found couple of examples, such as:

BasicDBObject query = new BasicDBObject();
BasicDBObject fields = new BasicDBObject("Name", 1);
coll.find(query, fields);

but all of them are designed for outdated version of MongoDB Java Driver, e.g. 2.4, while I'm using 3.2.

How can I query only specific fields of document in MongoDB Java Driver 3.2?


Solution

  • There is a .projection() method that is chainable to the query result which allows you to specify fields.

    Either expressed as a document, with the familiar and well documented BSON syntax:

        ArrayList<Document> unfecthedEvents = collection.find(
            new Document("fetchStatus", new Document("$lte", fetchStatusParam))
        ).projection(
            new Document("Name",1)
        ).into(new ArrayList<Document>());
    

    Or as a fields property builder which really just translates to exactly the same BSON:

        ArrayList<Document> unfecthedEvents = collection.find(
            new Document("fetchStatus", new Document("$lte", fetchStatusParam))
        ).projection(
                fields(include("Name"))
        ).into(new ArrayList<Document>());