5

如何查询一个字段而不是整个对象?我正在尝试做类似的事情,想看看这可能吗?

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);    
}
4

2 回答 2

7

在方法

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,则结果中的所有其他字段都将为空。

于 2013-03-25T07:43:14.230 回答
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());
    }
});
于 2016-03-15T08:50:48.557 回答