问题描述
实际上,您可以先使用“项目”来做类似的事情,但是对我来说, 事先需要一个阶段有点反常理:
Aggregation agg = newAggregation(
project("quantity")
.andExpression("dayOfMonth(date)").as("day")
.andExpression("month(date)").as("month")
.andExpression("year(date)").as("year")
.andExpression("price * quantity").as("totalAmount"),
group(fields().and("day").and("month").and("year"))
.avg("quantity").as("averavgeQuantity")
.sum("totalAmount").as("totalAmount")
.count().as("count")
);
就像我说的那样,违反直觉,因为您应该只可以在 舞台上声明所有这些内容,但是助手似乎并没有这样工作。序列化有点有趣(用数组包装date运算符参数),但是它确实起作用了。但是,这是两个流水线阶段,而不是一个。
这是什么问题?通过将阶段分开,“项目”部分会强制处理管道中的所有文档,以便获得计算出的字段,这意味着在进入分组阶段之前,它会经过所有步骤。
通过以两种形式运行查询,可以清楚地看到处理时间的差异。在一个单独的项目阶段,在我的硬件上执行该查询所需的时间比在“组”操作期间计算所有字段的查询要长三倍。
ApplicationContext ctx =
new AnnotationConfigApplicationContext(SpringMongoConfig.class);
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
BasicDBList pipeline = new BasicDBList();
String[] multiplier = { "$price", "$quantity" };
pipeline.add(
new BasicDBObject("$group",
new BasicDBObject("_id",
new BasicDBObject("month", new BasicDBObject("$month", "$date"))
.append("day", new BasicDBObject("$dayOfMonth", "$date"))
.append("year", new BasicDBObject("$year", "$date"))
)
.append("totalPrice", new BasicDBObject(
"$sum", new BasicDBObject(
"$multiply", multiplier
)
))
.append("averageQuantity", new BasicDBObject("$avg", "$quantity"))
.append("count",new BasicDBObject("$sum",1))
)
);
BasicDBObject aggregation = new BasicDBObject("aggregate","collection")
.append("pipeline",pipeline);
System.out.println(aggregation);
CommandResult commandResult = mongoOperation.executeCommand(aggregation);
或者,如果所有这些看起来都很麻烦,那么您始终可以使用JSON源进行解析。但是,当然,它必须是有效的JSON:
String json = "[" +
"{ \"$group\": { "+
"\"_id\": { " +
"\"month\": { \"$month\": \"$date\" }, " +
"\"day\": { \"$dayOfMonth\":\"$date\" }, " +
"\"year\": { \"$year\": \"$date\" } " +
"}, " +
"\"totalPrice\": { \"$sum\": { \"$multiply\": [ \"$price\", \"$quantity\" ] } }, " +
"\"averageQuantity\": { \"$avg\": \"$quantity\" }, " +
"\"count\": { \"$sum\": 1 } " +
"}}" +
"]";
BasicDBList pipeline = (BasicDBList)com.mongodb.util.JSON.parse(json);
解决方法
对于MongoDB文档中的示例,如何使用MongoTemplate编写查询?
db.sales.aggregate(
[
{
$group : {
_id : { month: { $month: "$date" },day: { $dayOfMonth: "$date" },year: { $year: "$date" } },totalPrice: { $sum: { $multiply: [ "$price","$quantity" ] } },averageQuantity: { $avg: "$quantity" },count: { $sum: 1 }
}
}
]
)
或一般来说,如何按计算字段分组?