Chris
Chris

Reputation: 3657

Spring Data Mongo - How to ask Mongo for the String ID

I have a projection and a groupby using Spring Data Mongo but at the moment when I call getMappedResults() I'm getting the BSON ID value rather than the String ID which I'd like.

Is it possible to ask Mongo to return the ID as a string? I know using raw queries I can call something like $toString: but how do I do this with my current codebase?

final ProjectionOperation dateProjection =
    project()
        .andInclude("_id", "name", "absolutePath")
        .and(dateField)
        .extractYear()
        .as("year");

final GroupOperation groupBy =
    group("year")
        .addToSet(
            new Document("id", "$_id") // How to get the String of the ID here
                .append("name", "$name")
                .append("absolutePath", "$absolutePath"))
        .as("results");

Upvotes: 1

Views: 219

Answers (1)

Vijay Rajpurohit
Vijay Rajpurohit

Reputation: 1352

You are almost there just need a small change in the group stage

final GroupOperation groupBy =
        group("year")
            .addToSet(
                new Document("id", new Document("$toString","$_id"))
                    .append("name", "$name")
                    .append("absolutePath", "$absolutePath"))
            .as("results");

This will return the string value.

Upvotes: 1

Related Questions