问题描述
我是mongo db的新手
我有 products 集合,其中包含一个 productSeasons
数组{
"_id" : "999999999","brand" : "BR","division" : "331","department" : "3314"
"productSeasons" : [
{
"season" : "FA","year" : "2020","status" : "ACTIVE","design": "DESIGN1"
},{
"season" : "FA","design": "DESIGN2"
},{
"season" : "SU","design": "DESIGN1"
}
]
}
我想根据季节,年份和状态字段返回带有匹配数组元素的文档。 我期望下面的标准输出为季节:FA,年份:2020,状态:ACTIVE 我正在使用Spring Mongo DB聚合框架
{
"_id" : "999999999","design": "DESIGN2"
}
]
}
我找不到正确的方法来创建具有多个字段,季节,年份,状态的AggregationExpression
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(where("_id").in(ids)),Aggregation.project("brand","division","department")
.and(
ArrayOperators.Filter.filter("productSeasons")
.as("productSeason")
.by(**Comparisonoperators.Cmp.valueOf("productSeason.season").compareto(prodSeason.getSeason())**)
)
.as("productSeasons")
);
预先感谢:)
解决方法
您必须使用以下阶段来获取所需的输出格式
db.collection.aggregate([
{
"$unwind": "$productSeasons"
},{
$match: {
"productSeasons.season": "FA","productSeasons.year": "2020","productSeasons.status": "ACTIVE"
}
},{
$group: {
"_id": "$_id","data": {
$push: "$$ROOT"
}
}
},{
"$project": {
"_id": 1,"department": {
$first: "$data.department"
},"productSeasons": "$data.productSeasons"
}
}
])
在Java中:
Aggregation.unwind
Aggregation.match
Aggregation.group
Aggregation.project
来自软件包org.springframework.data.mongodb.core.aggregation
如果您的 MongoDB 为 4.2.8 ,并且 Spring Data 为 3.0.3.RELEASE ,如下所示是用于创建聚合表达式的Java代码。
Criteria criteria = new Criteria();
Aggregation agg = Aggregation.newAggregation(
Aggregation.unwind("productSeasons"),Aggregation.match(criteria.and("productSeasons.season").is("FA")
.and("productSeasons.year").is("2020")
.and("productSeasons.status").is("ACTIVE")),Aggregation.group("_id").push(Aggregation.ROOT).as("data"),Aggregation.project("_id").and("data.brand").arrayElementAt(0).as("brand")
.and("data.division").arrayElementAt(0).as("division")
.and("data.department").arrayElementAt(0).as("department")
.and("data.productSeasons").as("productSeasons")
);
AggregationResults<Product> products = mongoOps.aggregate(agg,"product",Product.class);
注意:-您需要创建2个DTO, Product.java 是主类,而 ProductSeason.java 是数组元素的类,以创建上述代码。工作。