Spring 弹簧数据+;Mongodb+;查询单个值?

Spring 弹簧数据+;Mongodb+;查询单个值?,spring,mongodb,Spring,Mongodb,如何查询字段而不是整个对象?我正在尝试做类似的事情,想知道这可能吗 public BigInteger findUserIDWithRegisteredEmail(String email){ Query query = Query.query(Criteria.where("primaryEmail").is (email)); query.fields().include("_id"); return (BigInteger) mongoTemplate.

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

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);    
}
方法

find(Query query, Class<YourCollection> entityClass)
find(查询,类entityClass)
entityClass应该是相应的集合,而不是id的类型

如果你只是想用身份证

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

如果只包含_id,则结果中的所有其他字段都将为空

如果要避免序列化,这是一种处理方法:-

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());
    }
});
final List id=new ArrayList();
executeQuery(查询,“collectionName”,新文档CallbackHandler()){
@凌驾
public void processDocument(DBObject DBObject)抛出MongoException、DataAccessException{
add(dbObject.get(“_id”).toString();
}
});

感谢gTito,我的想法是尽量节省查询时间和带宽,只检索我需要的内容,而不是整个对象。那么,这是否意味着您必须获取整个文档(行)而不是字段,或者通过执行“query.fields().include(“_id”);”来获取?请注意,从数据库中只返回一个字段。是spring数据将值复制到字段并作为对象返回。如果只包含一个字段,则查询时间将缩短。但是有一件事你不能避免,那就是序列化所花费的时间。啊,这就是我试图避免序列化的原因。就像我使用ORM/hibernate一样,我可以使用直接sql查询一个字段而不是一个对象,所以我想在JavaNoSQL中我不能?或者有类似sql的东西吗?这很有趣,尽管在我的测试中,它比@titogeo发布的解决方案慢了一个数量级!