2013-03-25 36 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