2

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?

2 Answers 2

8

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>());
Sign up to request clarification or add additional context in comments.

1 Comment

Great, .projection(fields(include("Name"))) works as expected. Thanks.
0

It worked for me as well:

BasicDBObject whereQuery = new BasicDBObject();
BasicDBObject fields = new BasicDBObject();     

// the conditions in where query
whereQuery.put("dzeeClient", dzeeClient);
whereQuery.put("recommendationRunType", planView);
whereQuery.put("recommendedPlans.enrolled",employeeViewed);

// the fields to be returned from the query-only loginId, and remove _id
fields.put("loginId", 1); 
fields.put("_id", 0);

FindIterable<Document> cursor = collection.find(whereQuery)
                    .projection(fields).sort(new BasicDBObject("timeStamp",-1)).limit(1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.