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

时间:2016-03-19 22:47:40

标签: java mongodb query-optimization mongodb-query crud

我使用的是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>());

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

我找到了几个例子,例如:

BasicDBObject query = new BasicDBObject();
BasicDBObject fields = new BasicDBObject("Name", 1);
coll.find(query, fields);

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

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

3 个答案:

答案 0 :(得分:5)

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

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

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

或者作为fields属性构建器,它实际上只是转换为完全相同的BSON:

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

答案 1 :(得分:0)

它也对我有用:

BasicDBObject whereQuery = new BasicDBObject();
BasicDBObject fields = new BasicDBObject();     

// the conditions in where query
whereQuery.put("dzeeClient", dzeeClient);
whereQuery.put("recommendationRunType", planView);
whereQuery.put("recommendedPlans.enrolled",employeeViewed);

// the fields to be returned from the query-only loginId, and remove _id
fields.put("loginId", 1); 
fields.put("_id", 0);

FindIterable<Document> cursor = collection.find(whereQuery)
                    .projection(fields).sort(new BasicDBObject("timeStamp",-1)).limit(1);

答案 2 :(得分:-1)

包含一系列属性:.projection(Projections.include(&#34; Name&#34;)))

&安培;

排除属性列表:.projection(Projections.exclude(&#34; Name&#34;)))