Spring boot aggregation with String Operations(Trim)

368 views Asked by At

How can I write the below MongoDB operation into Java Springboot code?

db.collection.aggregate({
  "$group": {
    _id: {
      $trim: {
        input: "$name"
      }
    },
    doc: {
      "$first": "$$ROOT",
      
    }
  }
},
{
  "$replaceRoot": {
    "newRoot": "$doc"
  }
})
1

There are 1 answers

0
varman On

Hope you are using mongo template. You can use the BSON approach. TRICK TO CONVERT MONGO SHELL QUERY

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();

}

But you can also try this. Please make sure this is working

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();

}