Mongodb spring数据组_id降低或不区分大小写

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

我在春季启动时有mongodb facet和聚合查询,使用mongo模板和聚合查询。一切工作正常,除了值的大小写敏感。我在mongodb中有以下查询:

db.getCollection('product').aggregate([{"colors":[{$unwind:"$variants"},
{"$group": {
        _id: { $toLower: "$variants.color" },
        count:{$sum:1},
        image : { $first: '$variants.color_image' },
    }}

]

我有等效的弹簧数据查询:

Aggregation.facet(unwind("variants"), group("variants.color").count().as("count").first("variants.color_image").as("image"))
            .as("colors");

但是在这里我该如何提到降低分组字段?

mongodb spring-data-jpa mongodb-query aggregation-framework spring-data-mongodb
1个回答
1
投票

Spring-boot不允许像在shell中那样进行复杂的聚合。因此,您可以应用这样的解决方法

让我们以此来更改您的方面查询(在我们设置小写颜色值的地方创建新字段):

db.collection.aggregate([
  {
    $facet: {
      "colors": [
        {
          $unwind: "$variants"
        },
        {
          $addFields: {
            "variants.color_lower": {
              $toLower: "$variants.color"
            }
          }
        },
        {
          "$group": {
            _id: "$variants.color_lower",
            count: {
              $sum: 1
            },
            image: {
              $first: "$variants.color_image"
            },

          }
        }
      ]
    }
  }
])

MongoPlayground

现在,Spring-Boot允许定义自定义AggregationOperation(通用解决方案:here):

public class LowerAggregationOperation implements AggregationOperation() {

    @Override
    public List<Document> toPipelineStages(AggregationOperationContext context) {

        return Arrays.asList(
            new Document("$addFields", 
                new Document("variants.color_lower", 
                    new Document("$toLower", "$variants.color")))
        );
    }

}

现在,您完成了构面聚合:

Aggregation.facet(
    unwind("variants"), 
    new LowerAggregationOperation(),
    group("variants.color_lower").count().as("count").first("variants.color_image").as("image"))
.as("colors");
© www.soinside.com 2019 - 2024. All rights reserved.