mongodbaggregation-frameworkspring-data-mongodb

Array wrapper in projection with Spring Data MongoDB


I have a projection that involves creating a wrapper array (facets) and also create a field (name) with a constant.

AggregationOperation aggregationOperation = context -> Document.parse(
    """
          {
            "$project": {
                "products": 1,
                "count": {
                    "$arrayElemAt": [
                        "$count.count",
                        0
                    ]
                },
                "facets": [
                    {
                        "name": "PRODUCT_CATEGORY",
                        "items": "$productCategory"
                    }
                ]
            }
        }
        """);

I tried to write it using Spring Data Mongo Aggregation but I can't find the correct code to write. The first part works but for the facets part, it's not.

ProjectionOperation projectionOperation = project("products")
    .and("count.count").arrayElementAt(0).as("count")
    .and("facets").nested(bind("productCategory", "items"));

Solution

  • Document doc = new Document("name", "PRODUCT_CATEGORY").append("items", "$productCategory");
    
    ProjectionOperation projectionOperation = Aggregation
            .project("products")
            .and("count.count").arrayElementAt(0).as("count")
            .andArrayOf(doc).as("facets");