2013-03-25 55 views
4

如何查詢字段而不是整個對象?我正在嘗試做那樣的事情,想看看有沒有可能?Spring數據+ Mongodb +查詢單個值?

public BigInteger findUserIDWithRegisteredEmail(String email){ 

    Query query = Query.query(Criteria.where("primaryEmail").is (email));  
    query.fields().include("_id"); 

    return (BigInteger) mongoTemplate.find(query, BigInteger.class);  
} 

回答

5

在方法

find(Query query, Class<YourCollection> entityClass) 

entityClass應該相應集合而不是ID的類型。

如果你只是想獲得ID使用

Query query = Query.query(Criteria.where("primaryEmail").is (email));  
query.fields().include("_id"); 
mongoTemplate.find(query, <YourCollection>.class).getId(); 

如果只包括_id,所有其他字段將在您的結果無效。

+1

感謝gTito,我的想法是想節省查詢時間和帶寬只檢索什麼,我需要的,而不是整個對象。所以這意味着你必須得到整個文檔(行)而不是一個字段或通過做「query.fields()。include(」_ id「);」其實是這樣做的? – Jaxox 2013-03-25 20:44:44

+1

請注意,從db中只返回一個字段。它是將數值複製到字段並作爲對象返回的彈簧數據。如果只包含一個字段,則查詢時間會縮短。但是你無法避免的一件事是序列化所花費的時間。 – titogeo 2013-03-27 06:38:24

+0

啊這就是我想要避免序列化。就像我使用ORM/hibernate一樣,我可以使用直接sql查詢一個字段,而不是一個對象,所以我想在java nosql中我不能?或者有什麼像SQL? – Jaxox 2013-03-27 15:38:38

0

如果你想避免序列,這是你能處理的一種方式: -

final List<String> ids = new ArrayList<String>(); 
mongoTemplate.executeQuery(query, "collectionName", new DocumentCallbackHandler() { 
    @Override 
    public void processDocument(DBObject dbObject) throws MongoException, DataAccessException { 
     ids.add(dbObject.get("_id").toString()); 
    } 
}); 
+0

這很有趣,雖然在我的測試中它比@titogeo發佈的解決方案慢了一個數量級! – Madbreaks 2017-02-02 18:55:31