Mongodb spring 数据组_id toLower or case insensitive
Mongodb spring data group _id toLower or case insensitive
我在 spring 启动时使用 mongo 模板和聚合查询进行了 mongodb 方面和聚合查询。一切正常,除了值的大小写敏感性。我在 mongodb:
中有以下查询
db.getCollection('product').aggregate([{"colors":[{$unwind:"$variants"},
{"$group": {
_id: { $toLower: "$variants.color" },
count:{$sum:1},
image : { $first: '$variants.color_image' },
}}
]
我有等效的spring数据查询:
Aggregation.facet(unwind("variants"), group("variants.color").count().as("count").first("variants.color_image").as("image"))
.as("colors");
但是这里怎么能提到toLower to group字段呢?
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"
},
}
}
]
}
}
])
现在,Spring-Boot 允许定义自定义 AggregationOperation (Generic solution: ):
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")))
);
}
}
现在,您完成了 facet 聚合:
Aggregation.facet(
unwind("variants"),
new LowerAggregationOperation(),
group("variants.color_lower").count().as("count").first("variants.color_image").as("image"))
.as("colors");
我在 spring 启动时使用 mongo 模板和聚合查询进行了 mongodb 方面和聚合查询。一切正常,除了值的大小写敏感性。我在 mongodb:
中有以下查询db.getCollection('product').aggregate([{"colors":[{$unwind:"$variants"},
{"$group": {
_id: { $toLower: "$variants.color" },
count:{$sum:1},
image : { $first: '$variants.color_image' },
}}
]
我有等效的spring数据查询:
Aggregation.facet(unwind("variants"), group("variants.color").count().as("count").first("variants.color_image").as("image"))
.as("colors");
但是这里怎么能提到toLower to group字段呢?
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"
},
}
}
]
}
}
])
现在,Spring-Boot 允许定义自定义 AggregationOperation (Generic solution:
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")))
);
}
}
现在,您完成了 facet 聚合:
Aggregation.facet(
unwind("variants"),
new LowerAggregationOperation(),
group("variants.color_lower").count().as("count").first("variants.color_image").as("image"))
.as("colors");