【问题标题】:Spring data + Mongodb + query single value?Spring Data + Mongodb + 查询单值?
【发布时间】:2013-03-14 13:09:45
【问题描述】:

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

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

【问题讨论】:

    标签: spring mongodb


    【解决方案1】:

    在方法中

    find(Query query, Class<YourCollection> entityClass)
    

    entityClass应该是对应的collection,而不是id的类型。

    如果你只是想获得 id 使用

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

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

    【讨论】:

    • 感谢 gTito,我的想法是尝试节省查询时间和带宽,以便仅检索我需要的内容而不是整个对象。这是否意味着您必须获取整个文档(行)而不是字段或通过执行“query.fields().include("_id");"真的是这样吗?
    • 请注意,从 db 中只返回一个字段。将值复制到字段并作为对象返回的是 spring-data。如果您只包含一个字段,您的查询时间会更少。但是您无法避免的一件事是序列化所花费的时间。
    • 啊,这就是我试图避免序列化的原因。就像我使用 ORM / hibernate 一样,我可以使用直接 sql 来查询一个字段而不是一个对象,所以我猜在 java nosql 中我不能?或者有什么类似sql的吗?
    【解决方案2】:

    如果您想避免序列化,这是您可以处理的一种方法:-

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

    【讨论】:

    • 这很有趣,尽管在我的测试中它比@titogeo 发布的解决方案慢一个数量级!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 2018-11-25
    • 2020-10-07
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多