Java mongodb mongoTemplate 使用某些条件获取不同的字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31635677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:20:35  来源:igfitidea点击:

mongodb mongoTemplate get distinct field with some criteria

javamongodbspring-mongodb

提问by Raj

My MongoDB json structure is

我的 MongoDB json 结构是

 {
    "_id" : "122134231234234",
    "name" : "Total_pop",
    "description" : "sales category",
    "source" : "public",
    "dataset" :"d1"


},
{
    "_id" : "1123421231234234",
    "name" : "Total_pop",
    "description" : "sales category",
    "source" : "public",
    "dataset" :"d1"


},
{
    "_id" : "12312342332423343",
    "name" : "Total_pop",
    "description" : "sales category",
    "source" : "private",
    "description" : "d1"
}

I need to get collection distinct of dataset where source is public. I tried this query, and it didn't work:

我需要获取与数据集不同的集合,其中源是公开的。我试过这个查询,但没有奏效:

Criteria criteria = new Criteria();
criteria.where("source").in("public");     
query.addCriteria(criteria);
query.fields().include("name");
query.fields().include("description");
query.fields().include("description");
query.fields().include("source"); List list =
mongoTemplate.getCollection("collectionname").distinct("source", query);

Can you please help me out?

你能帮我一下吗?

采纳答案by Blakes Seven

For one thing the .getCollection()method returns the basic Driver collection object like so:

一方面,该.getCollection()方法返回基本的 Driver 集合对象,如下所示:

DBCollection collection = mongoTemplate.getCollection("collectionName");

So the type of query object might be different from what you are using, but there are also some other things. Namely that .distinct()only returns the "distint" values of the key that you asked for, and doe not return other fields of the document. So you could do:

所以查询对象的类型可能与您使用的不同,但还有一些其他的东西。即.distinct()只返回您要求的键的“distint”值,而不返回文档的其他字段。所以你可以这样做:

Criteria criteria = new Criteria();
criteria.where("dataset").is("d1");
Query query = new Query();
query.addCriteria(criteria);
List list = mongoTemplate.getCollection("collectionName")
    .distinct("source",query.getQueryObject());

But that is only going to return "sample" as a single element in the list for instance.

但这只会将“sample”作为列表中的单个元素返回。

If you want the "fields" from a distinct set then use the .aggregate()method instead. With either the "first" occurances of the other field values for the distinct key:

如果您想要来自不同集合的“字段”,请改用该.aggregate()方法。使用不同键的其他字段值的“第一次”出现:

    DBCollection colllection = mongoTemplate.getCollection("collectionName");

    List<DBObject> pipeline = Arrays.<DBObject>asList(
        new BasicDBObject("$match",new BasicDBObject("dataset","d1")),
        new BasicDBObject("$group",
            new BasicDBObject("_id","$source")
                .append("name",new BasicDBObject("$first","$name"))
                .append("description", new BasicDBObject("$first","$description"))
        )
    );

    AggregationOutput output = colllection.aggregate(pipeline);

Or the actual "distinct" values of multiple fields, by making them all part of the grouping key:

或者多个字段的实际“不同”值,通过使它们全部成为分组键的一部分:

    DBCollection colllection = mongoTemplate.getCollection("collectionName");

    List<DBObject> pipeline = Arrays.<DBObject>asList(
        new BasicDBObject("$match",new BasicDBObject("dataset","d1")),
        new BasicDBObject("$group",
            new BasicDBObject("_id",
                new BasicDBObject("source","$source")
                    .append("name","$name")
                    .append("description","$description")
            )
        )
    );

    AggregationOutput output = colllection.aggregate(pipeline);

There are also a direct .aggregate()method on mongoTemplate instances already, which has a number of helper methods to build pipelines. But this should point you in the right direction at least.

.aggregate()mongoTemplate 实例上也有一个直接方法,它有许多构建管道的辅助方法。但这至少应该为您指明正确的方向。

回答by user3009002

As of Spring Data Mongo 2.2.0 MongoTemplate provides a function to retrieve the distinct field with criteria,

从 Spring Data Mongo 2.2.0 MongoTemplate 开始,提供了一个函数来检索具有条件的不同字段,

Criteria criteria = new Criteria("country").is("IN");
Query query = new Query();
query.addCriteria(criteria);
return mongoTemplate.findDistinct(query,"city",Address.class,String.class);

Which basically finds all the distinct cities in address collection where country is IN.

这基本上可以找到地址集合中国家为 IN 的所有不同城市。