![](/img/trans.png)
[英]How to return only specific fields for a query in Spring Data MongoDB?
[英]How to query only the specific fields in MongoDB with Java?
我正在使用 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 中僅查詢文檔的特定字段?
有一個.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>());
它也對我有用:
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);
我正在使用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中的文檔的特定字段?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.