简体   繁体   English

如何使用投影和过滤器区分 MongoDB 中的查询?

[英]How to distinct query in MongoDB with projection and filters?

I have list of attributes in mongo and I am querying some nested field.我在 mongo 中有属性列表,并且正在查询一些嵌套字段。 Here is my code,这是我的代码,

public List<Brand> searchBrands(Request request) {
    final MongoCollection<Document> collection = mongoDatabase.getCollection("shop");
    final Document query = new Document();
    final Document projection = new Document();
    final List<Brand> brandList = new ArrayList<>();


    query.append("_id", request.getId());
    query.append("isActive", true);
    if (request.Year() != null) {
        query.append("attributes.name", "myYear");
        query.append("attributes.value", request.getYear());
    }

    projection.append("brand.code", 1.0);
    projection.append("brand.description", 1.0);
    projection.append("_id", 0.0);



    Block<Document> processBlock = document -> brandList.
            add(Brand.builder().code(document.get("brand",Document.class).getString("code"))
                    .description(document.get("brand",Document.class).getString("description"))
                    .build());


    collection.find(query).projection(projection).forEach(processBlock);

    return brandList;}

Above code return results correctly, 72 item with same brand.code.以上代码正确返回结果,72 项具有相同的brand.code。 But I want to fetch distinct according to brand.code How can I do that?但是我想根据brand.code获取不同的信息我该怎么做?

I'm not sure which mongodb client library you're using to create queries for mongodb;我不确定您使用哪个 mongodb 客户端库来为 mongodb 创建查询; I'm sharing the query that you can run in mongodb console to get the results you want.我正在分享您可以在 mongodb 控制台中运行的查询以获得您想要的结果。 I hope you know how to create this query using your mongodb client library我希望您知道如何使用您的 mongodb 客户端库创建此查询

db.shop.distinct('brand.code', myQuery)
//Replace myQuery with your query e.g. {isActive: true}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM