0

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

1
  • you can find the answer in this post Here's a link Commented May 7, 2022 at 22:55

2 Answers 2

1

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

Comments

1

I improved it by adding .append("id",0) to the projection

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

this now returns what I need Document{{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}}

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.