是否可以在 Spring 数据 MongoDB 中将 group() 与 ArrayOperators.arrayOf() 结合使用?
Is it possible to use group() in combination with ArrayOperators.arrayOf() in Spring Data MongoDB?
给定数据:
{
"_id" : ObjectId("58b7fb9acdcf58886fa86136"),
"cost" : 50,
"nodes" : [
4, 8, 15, 16, 23, 42
]
}
{
"_id" : ObjectId("58b7fba3cdcf58886fa86137"),
"cost" : 25,
"nodes" : [
1, 2, 3, 4, 23, 6
]
}
{
"_id" : ObjectId("58b7fbaecdcf58886fa86138"),
"cost" : 75,
"nodes" : [
1, 2, 17, 19, 20, 21
]
}
我可以在 MongoDB 中使用聚合来按数组中的第二个元素分组,如下所示:
db.stuff.aggregate([
{
"$group": {
"_id": {"$arrayElemAt": ["$nodes", 1]},
"costs": {$sum: "$cost"}
}
}])
在 Spring 数据 MongoDB 中,我最终使用以下 Java 代码得到相同的结果:
Aggregation aggTest = Aggregation.newAggregation(
project()
.and(ArrayOperators.arrayOf("nodes").elementAt(1)).as("node")
.and("cost").as("cost"),
group("node").sum("cost").as("costs")
);
是否可以在 Spring 数据 MongoDB 中将 group() 与 ArrayOperators.arrayOf().elementAt 结合使用,从而删除额外的 project()?
看起来 spring mongo 的小组赛阶段 AggregationExpression
没有 _id
。
您可以尝试创建一个AggregationOperation
AggregationOperation group = new AggregationOperation() {
@Override
public DBObject toDBObject(AggregationOperationContext context) {
return new BasicDBObject(
"$group", new BasicDBObject(
"_id", new BasicDBObject(
"$arrayElemAt", Arrays.asList("nodes", 1))).append(
"costs", new BasicDBObject("$sum", "cost")));
}
};
Aggregation agg = Aggregation.newAggregation(group);
给定数据:
{
"_id" : ObjectId("58b7fb9acdcf58886fa86136"),
"cost" : 50,
"nodes" : [
4, 8, 15, 16, 23, 42
]
}
{
"_id" : ObjectId("58b7fba3cdcf58886fa86137"),
"cost" : 25,
"nodes" : [
1, 2, 3, 4, 23, 6
]
}
{
"_id" : ObjectId("58b7fbaecdcf58886fa86138"),
"cost" : 75,
"nodes" : [
1, 2, 17, 19, 20, 21
]
}
我可以在 MongoDB 中使用聚合来按数组中的第二个元素分组,如下所示:
db.stuff.aggregate([
{
"$group": {
"_id": {"$arrayElemAt": ["$nodes", 1]},
"costs": {$sum: "$cost"}
}
}])
在 Spring 数据 MongoDB 中,我最终使用以下 Java 代码得到相同的结果:
Aggregation aggTest = Aggregation.newAggregation(
project()
.and(ArrayOperators.arrayOf("nodes").elementAt(1)).as("node")
.and("cost").as("cost"),
group("node").sum("cost").as("costs")
);
是否可以在 Spring 数据 MongoDB 中将 group() 与 ArrayOperators.arrayOf().elementAt 结合使用,从而删除额外的 project()?
看起来 spring mongo 的小组赛阶段 AggregationExpression
没有 _id
。
您可以尝试创建一个AggregationOperation
AggregationOperation group = new AggregationOperation() {
@Override
public DBObject toDBObject(AggregationOperationContext context) {
return new BasicDBObject(
"$group", new BasicDBObject(
"_id", new BasicDBObject(
"$arrayElemAt", Arrays.asList("nodes", 1))).append(
"costs", new BasicDBObject("$sum", "cost")));
}
};
Aggregation agg = Aggregation.newAggregation(group);