Chris
Chris

Reputation: 3657

MongoDB Group operation return document rather than single fields

I'm trying to group a collection of files based on when they where last accessed according to data I have in Mongo.

However I'm unsure how to return more of a Document from a group operation.

How do I get back a document with all the information under each grouping?

For example I'm now returning:

[
  {
    "year": [
      2020
    ],
    "month": [
      2
    ],
    "week": [
      7
    ],
    "day": [
      2
    ],
    "results": [
      "filename-1",
      "filename-2"
    ]
  }
]

I'm only getting the filename back in a basic array. I'd like the document rather than just the name.

The code I'm using to create the result above

  public void groupTest() {

    final String dateField = "lastAccessTime";

    final LocalDate now = LocalDate.now();
    final LocalDate firstDay = now.with(firstDayOfYear());
    final LocalDate lastDay = now.with(lastDayOfYear());

    final Criteria criteria =
        new Criteria().andOperator(where(dateField).gte(firstDay), where(dateField).lte(lastDay));

    final ProjectionOperation dateProjection =
        project()
            .and("_id")
            .as("id")
            .and("name")
            .as("name")
            .and("absolutePath")
            .as("absolutePath")
            .and(dateField)
            .extractYear()
            .as("year")
            .and(dateField)
            .extractMonth()
            .as("month")
            .and(dateField)
            .extractWeek()
            .as("week")
            .and(dateField)
            .extractDayOfWeek()
            .as("day");

    final GroupOperation groupBy =
        group("year", "month", "week", "day")
                .addToSet("name")
                .as("results");

    final Aggregation aggregation =
        newAggregation(
            match(criteria),
            dateProjection,
            groupBy,
            sort(Sort.Direction.ASC, "year", "month", "week", "day"));
  }

I'd like my results value to be more like:

[
  {
    "year": [
      2020
    ],
    "month": [
      2
    ],
    "week": [
      7
    ],
    "day": [
      2
    ],
    "results": [
      {
        "id": "123",
        "filename": "filename-1",
        "size": 30000
      },
      {
        "id": "456",
        "filename": "filename-2",
        "size": 30000
      }
    ]
  }
]

Any help is very much appreciated

Upvotes: 0

Views: 427

Answers (1)

Valijon
Valijon

Reputation: 13113

Change your group stage to this:

GroupOperation group = Aggregation
    .group("year", "month", "week", "day")
    .addToSet(new Document("id", "$id")
                   .append("filename", "$name")
                   .append("size", "$size"))
    .as("results");

Note: Make sure to include size field into dateProjection stage.

Upvotes: 1

Related Questions