如何使用Java仅查询MongoDB中的特定字段

Mik*_* B. 1 java crud query-optimization mongodb mongodb-query

我正在使用MongoDB 3.2和MongoDB Java Driver 3.2.为了查询文档,我使用以下代码:

Document query = new Document("fetchStatus", new Document("$lte", fetchStatusParam));
ArrayList<Document> unfetchedEvents = dbC_Events.find(query).into(new ArrayList<Document>());
Run Code Online (Sandbox Code Playgroud)

此查询有效,但问题是在这种情况下,将检索文档的所有字段(select *在SQL中类似).为了优化查询性能,我想指定我真正需要的字段并仅获取它们.

我发现了几个例子,例如:

BasicDBObject query = new BasicDBObject();
BasicDBObject fields = new BasicDBObject("Name", 1);
coll.find(query, fields);
Run Code Online (Sandbox Code Playgroud)

但是所有这些都是针对过时版本的MongoDB Java驱动程序设计的,例如2.4,而我使用的是3.2.

我的问题:
如何只查询MongoDB Java Driver 3.2中的特定文档字段?

Bla*_*ven 5

有一个.projection()可链接到查询结果的方法,允许您指定字段.

使用熟悉且记录良好的BSON语法表达为文档:

    ArrayList<Document> unfecthedEvents = collection.find(
        new Document("fetchStatus", new Document("$lte", fetchStatusParam))
    ).projection(
        new Document("Name",1)
    ).into(new ArrayList<Document>());
Run Code Online (Sandbox Code Playgroud)

或者作为一个fields属性构建器,它真正转换为完全相同的BSON:

    ArrayList<Document> unfecthedEvents = collection.find(
        new Document("fetchStatus", new Document("$lte", fetchStatusParam))
    ).projection(
            fields(include("Name"))
    ).into(new ArrayList<Document>());
Run Code Online (Sandbox Code Playgroud)