$filter inside $project MongoDB Using Spring Data

馋奶兔 提交于 2019-11-29 12:49:37
Daniel Henao

I managed to solve my problem with the Spring boot Version 1.4.1.RELEASE and I did this:

Aggregation aggregation = newAggregation(
            match(Criteria.where("devices.evaluationDate").is(date)),
            project().and(new AggregationExpression() {
                @Override
                public DBObject toDbObject(AggregationOperationContext aggregationOperationContext) {
                    DBObject filterExpression = new BasicDBObject();
                    filterExpression.put("input", "$devices");
                    filterExpression.put("as", "device");
                    filterExpression.put("cond", new BasicDBObject("$eq", Arrays.<Object> asList("$$device.evaluationDate", date)));
                    return new BasicDBObject("$filter", filterExpression);
                }
            }).as("devices")
    );

    AggregationResults<SpotMovimientos> list = mongoOperations.aggregate(aggregation,
            MyClass.class, MyClass.class);

I elaborated based on this: Does Spring Data MongoDb support $filter array aggregations operator?

My project was on Spring boot 1.4.0.RELEASE but that version didnt have the AggregationExpression interface PUBLIC, so i just updated to 1.4.1.RELEASE and i did work.

And this is how it's made in spring-data-monogodb-2.0.10 (Spring Boot 2)

Aggregation aggregation = newAggregation(
                match(Criteria.where("devices.evaluationDate").is(date)),
                project().and(new AggregationExpression() {
                    @Override
                    public Document toDocument(AggregationOperationContext aggregationOperationContext) {
                        Document filterExpression = new Document();
                        filterExpression.put("input", "$devices");
                        filterExpression.put("as", "device");
                        filterExpression.put("cond", new Document("$eq", Arrays.<Object> asList("$$device.evaluationDate", date)));
                        return new Document("$filter", filterExpression);
                    }
                }).as("devices")
        );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!