Search code examples
javamongodbmongodb-java

Return only results of specific field - Mongodb java


Hello I am using MONGODB java driver version 4.5.1, I created a method to query a document and grab a specific field.

(id is a discord id not document _id)

final MONGODB mongodb = new MONGODB();
    public ArrayList<Document> getRoom(long id) {
        ArrayList<Document> results = mongodb.collection.find(
                new Document("id",id)
        ).projection(
                new Document("room",1)
        ).into(new ArrayList<>());
        System.out.println(results.size());
        for (Document result : results) {
            System.out.println(result);
        }
        return results;
    }

this returns Document{{_id=6276ed329a9a491cc223ae32, room=pt pt pt pt pt nl pt pt pt pt pt nl pt pt pt pt pt nl pt pt pt pt pt nl pt pt pt pt pt nl}}

I am looking to improve this to only have it return the contents of room=, and not the _id field


Solution

  • The term for this is projection, you can have a look at: https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results/

    As the documentation suggests;

    You can remove the _id field from the results by setting it to 0 in the projection, as in the following example:

    findIterable = collection.find(eq("status", "A"))
        .projection(fields(include("item", "status"), excludeId()))