我希望使用spring数据从mongodb获得一个字段的不同值的结果

问题描述 投票:4回答:1

我希望使用spring数据从mongodb获得一个字段的不同值的结果。我的代码是

Query query = new Query();

    query.addCriteria(Criteria.where("to.toId").in(toIdList));
    query.fields().include("from");
    query.fields().include("fromName");
    query.fields().include("sentTime");
    query.fields().include("hasAttachment");
    newMessages = mongoTemplate.find(query, NewMessage.class);
mongodb spring-data-mongodb
1个回答
8
投票

您可以使用distinct而不是find:

db.mycollection.distinct('fieldname', query)

使用SpringData语法应该是这样的:

mongoTemplate.getCollection(collection).distinct(key, query)
© www.soinside.com 2019 - 2024. All rights reserved.