Spring boot aggregation with group Trim



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 "
  }
]

Answer

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.



Source: stackoverflow