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

10,070

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>());
Share:
10,070
Mike
Author by

Mike

I'm a software engineer with a passion for code quality.

Updated on June 04, 2022

Comments

  • Mike
    Mike almost 2 years

    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.

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

  • Mike
    Mike about 8 years
    Great, .projection(fields(include("Name"))) works as expected. Thanks.