mongodb - 带有字符串操作的 Spring Boot 聚合(Trim)
问题描述
如何将以下 MongoDB 操作写入 Java Springboot 代码?
db.collection.aggregate({
"$group": {
_id: {
$trim: {
input: "$name"
}
},
doc: {
"$first": "$$ROOT",
}
}
},
{
"$replaceRoot": {
"newRoot": "$doc"
}
})
解决方案
希望您使用的是 mongo 模板。您可以使用 BSON 方法。转换 MONGO SHELL 查询的技巧
public List<Object> test() {
Aggregation aggregation = Aggregation.newAggregation(
p-> new Document("$group",
new Document("_id",
new Document("$trim",
new Document("input","$name")
)
).append("doc",
new Document("$first","$$ROOT")
)
),
replaceRoot("doc")
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
}
但你也可以试试这个。请确保这是有效的
public List<Object> test() {
Aggregation.newAggregation(
group("$_id".trim()).first("$$ROOT").as("doc"),
replaceRoot("doc")
)
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
}
推荐阅读
- java - Maven:更改插件更深的依赖版本
- kendo-ui - Kendo Jquery pdf viewer 如何自定义 pdf 页面视图。?
- ios - 从 alomofire 发布请求中解析错误
- php - PHP 如何使用(PHP/Composer/AJAX)在网站上以毫秒显示客户端 ping?
- notion-api - API:关系属性
- google-apps-script - 删除“访问驱动器”权限以运行电子表格绑定的应用程序脚本
- apache-flink - Flink Redis 接收流
- sql - SQL / Presto 错误:TYPE_MISMATCH:逻辑表达式的左侧必须计算为布尔值(实际:varchar)
- antlr4 - ANTLR 解析器为“true and or false”语句抛出异常
- docker - 下载图像时出现 500 内部服务器错误