Return 仅特定字段的结果 - Mongodb java

Return only results of specific field - Mongodb java

您好,我正在使用 MONGODB java 驱动程序版本 4.5.1,我创建了一个查询文档并获取特定字段的方法。

(id 是一个 discord id 而不是文档 _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;
    }

这个return秒 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}}

我希望将其改进为只有 return room= 的内容,而不是 _id 字段

这个叫projection,你可以看看:https://www.mongodb.com/docs/manual/tutorial/project-fields-from-query-results/

如文档所示;

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

我通过添加对其进行了改进 .append("id",0) 到投影

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

这是我现在需要的 returns 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}}