简体   繁体   中英

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

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()))

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}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM