问题描述
考虑在字段中包含空格的集合,如果我们将它们分组为Ravi",则在 DB 中是否有空格拉维, 考虑为总共 2 个值.但它应该被视为单一值.所以我在组中修剪.我曾在 DB 中表演过.但我不知道如何在 Springboot 中修剪和分组值.我们可以在 Springboot 中为此使用聚合.但不知道如何使用修剪.请对此提供帮助
样本集:
[{名称":拉维",DOB":04-02-2000",血液":A1+"},{名称":拉维",DOB":05-03-2000",血液":A1+"},{名称":库马尔",DOB":02-04-2000",血液":A1+"},{名称":库马尔",DOB":03-05-2000",血液":A1+"}]MongoDB 操作:
db.collection.aggregate({$组":{_ID: {$修剪:{输入:$name"}},文档:{$first":$$ROOT",}}},{$replaceRoot":{newRoot":$doc"}})
输出:
[{血液":A1+",DOB":04-02-2000",_id":ObjectId(5a934e000102030405000000"),名称":拉维"},{血液":A1+",DOB":02-04-2000",_id":ObjectId(5a934e000102030405000002"),名称":库马尔"}]无法通过标准 API 实现.
解决方法:在应用 $group
阶段之前,我们需要添加额外的 $addFields
来修剪 name
字段.
@Autowired私有 MongoTemplate 模板;...聚合 agg = Aggregation.newAggregation(Aggregation.addFields().addFieldWithValue("name", Trim.valueOf("name")).build(),Aggregation.group(名称").first("$$ROOT").as("doc"),Aggregation.replaceRoot(doc"));...template.aggregate(agg, inputType, outputType);
注意:由于您在第一阶段操作了 name
字段,MongoDB 不会使用索引,因此我们可以向管道添加一个额外的阶段.
Consider collection with whitespace in field, in DB if there is white space if we group them "Ravi", " Ravi " , consider as total 2 values. but it should consider as single value. So I have trim in Group. I had performed in DB. But I don't know how can I trim and group value in Springboot. We can use Aggregation for this in Springboot. but don't how to use trim. Kindly help on this
Sample Collection:
[
{
"name": "ravi",
"DOB": "04-02-2000",
"Blood": "A1+"
},
{
"name": "ravi ",
"DOB": "05-03-2000",
"Blood": "A1+"
},
{
"name": "kumar ",
"DOB": "02-04-2000",
"Blood": "A1+"
},
{
"name": "kumar",
"DOB": "03-05-2000",
"Blood": "A1+"
}
]
MongoDB Operation:
db.collection.aggregate({
"$group": {
_id: {
$trim: {
input: "$name"
}
},
doc: {
"$first": "$$ROOT",
}
}
},
{
"$replaceRoot": {
"newRoot": "$doc"
}
})
Output:
[
{
"Blood": "A1+",
"DOB": "04-02-2000",
"_id": ObjectId("5a934e000102030405000000"),
"name": "ravi"
},
{
"Blood": "A1+",
"DOB": "02-04-2000",
"_id": ObjectId("5a934e000102030405000002"),
"name": "kumar "
}
]
Not possible via standard API.
Workaround: We need to add extra $addFields
to trim the name
field before applying $group
stage.
@Autowired
private MongoTemplate template;
...
Aggregation agg = Aggregation.newAggregation(
Aggregation.addFields()
.addFieldWithValue("name", Trim.valueOf("name")).build(),
Aggregation.group("name")
.first("$$ROOT").as("doc"),
Aggregation.replaceRoot("doc")
);
...
template.aggregate(agg, inputType, outputType);
Note: Since you were manipulating the name
field in the first stage, MongoDB wouldn't use indexes, so we can add an extra stage to the pipeline.
这篇关于Spring Boot 聚合与组 Trim的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!