excedion
excedion

Reputation: 347

Spring Data Mongo returns lists instead of string

In my Spring Boot application, I am querying a collection of documents. I'm trying to perform an aggregate operation, to group similar fields together and count them.

The issue is that while the right values are being returned, they should be just normal strings "[ \"Test Name\"]" should be "Test Name"

I can solve this issue for one of the fields by using the @Id annotation but spring data Mongo does not like composite keys so I can not use that as a solution.

How can I return just the string value and not the values that are given below.

{
    "exampleDateTime": 1392029442389,
    "exampleName": "[ \"Test Name\"]",
    "exampleDescription": "[ \"Test Description\"]",
    "exampleCount": 1
}

So I have a java object like this

@Document(collection = "ExampleCollection")
public class Example{
    private Date exampleDateTime;
    private String exampleName;
    private String exampleDescription;
    private int exampleCount;

    ...getters and setters...
}

The Repository Implementation with Aggregation

    public class ExampleRepositoryImpl implements ExampleRepositoryCustom {


     @Autowired
     MongoTemplate mongoTemplate;

    @Override
    public List<Example> countExampleByName() {
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.group("exampleName").addToSet("exampleName").as("exampleName").addToSet("exampleDateTime").as("exampleDateTime")
                .addToSet("exampleDescription").as("exampleDescription").count().as("exampleCount")

        AggregationResults<Example> groupResults = mongoTemplate.aggregate(
                aggregation,"ExampleCollection", Example.class);

        List<Example> result = groupResults.getMappedResults();
        return result;
    }
}

Upvotes: 1

Views: 1878

Answers (1)

s7vr
s7vr

Reputation: 75934

When you use addToSet, which returns collection type, spring calls toString() to convert it to string type ( note the quotes around [] ) as defined in your pojo

Replace your aggregation to use first with

Aggregation aggregation = Aggregation.newAggregation( 
        Aggregation.group("exampleName")
           .first("exampleName").as("ex‌​ampleName")
           .first("e‌​xampleDateTime").as(‌​"exampleDateTime") 
           .first("exampleDescription").as("exampleDescription")
           .count(‌​).as("exampleCount")

OR

Change your types in pojo to String[] or collection of string if you need to use addToSet

Upvotes: 2

Related Questions