0

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"
  }
})
James Z
  • 12,209
  • 10
  • 24
  • 44
hodophiler
  • 13
  • 3
  • Does this answer your question? [Spring boot aggregation with group Trim](https://stackoverflow.com/questions/67539150/spring-boot-aggregation-with-group-trim) – Valijon May 16 '21 at 10:23

1 Answers1

0

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

}
varman
  • 8,704
  • 5
  • 19
  • 53