Filter array in sub-document array field in Spring framework

两盒软妹~` 提交于 2019-12-02 10:52:53

You can try the following but you'll need to use 1.8.5 version.

Aggregation aggregation = newAggregation(
            project("_id").and(new AggregationExpression() {
                @Override
                public DBObject toDbObject(AggregationOperationContext aggregationOperationContext) {
                    DBObject filter = new BasicDBObject("input", "$$item.columns").append("as", "elt").append("cond",
                            new BasicDBObject("$eq", Arrays.<Object>asList("$$elt.title", "hahaha")));
                    DBObject map = new BasicDBObject("input", "$items").append("as", "item").append("in", filter);
                    return new BasicDBObject("$map", map);
                }
            }).as("items")
  );

The support for some of Mongo3.2 aggregation operators were added in 1.10.0.RC1. If you are okay with updating to release candidate version you can use the below version. I couldn't find $addFields stage in the RC so kept the $project stage.

Aggregation aggregation = newAggregation(
            project("_id")
                    .and(mapItemsOf("items").as("item").andApply(filter("item.columns")
                            .as("elt")
                            .by(valueOf("elt.title").equalToValue("hahaha"))
                    )).as("items")
);

Static Imports:

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import static org.springframework.data.mongodb.core.aggregation.ArrayOperators.Filter.filter;
import static org.springframework.data.mongodb.core.aggregation.ComparisonOperators.Eq.valueOf;
import static org.springframework.data.mongodb.core.aggregation.VariableOperators.mapItemsOf;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!