【问题标题】:How to query only the specific fields in MongoDB with Java?如何使用 Java 仅查询 MongoDB 中的特定字段?
【发布时间】:2016-07-06 14:39:18
【问题描述】:

我正在使用 MongoDB 3.2 和 MongoDB Java 驱动程序 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 中仅查询文档的特定字段?

【问题讨论】:

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


    【解决方案1】:

    它也对我有用:

    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】:

      有一个.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>());
      

      【讨论】:

      • 太好了,.projection(fields(include("Name"))) 按预期工作。谢谢。
      猜你喜欢
      • 2015-11-13
      • 2012-11-20
      • 2015-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多