[英]Does Spring Data MongoDb support $filter array aggregations operator?
I'm trying to implement in Spring Data using MongoTemplate the following working mongoDb query:我正在尝试使用 MongoTemplate 在 Spring Data 中实现以下工作 mongoDb 查询:
db.answers.aggregate([
{ "$match" : { "object_id" : "1" } },
{ "$project": { 'answer_list': 1, 'profile': { $filter : { input: '$answer_list', as: 'answer', cond: { $eq: [ '$$answer.question', 2 ] } } } } },
{ "$unwind" : "$profile"},
{ "$unwind" : "$answer_list"},
{ "$group" : { "_id" : { "question" : "$answer_list.question", "answer" : "$answer_list.answer", "criteria" : "$profile.answer"}, "count" : { "$sum" : 1 } } },
{ "$sort" : { "_id.question" : 1, "_id.answer" : 1 } }
]);
The collection has this structure:该集合具有以下结构:
{
"_id" : ObjectId("..."),
"object_id" : ObjectId("..."),
"answer_list" : [
{
"question" : NumberLong(0),
"answer" : NumberLong(0)
},
{
"question" : NumberLong(1),
"answer" : NumberLong(2)
},
{
"question" : NumberLong(2),
"answer" : NumberLong(2)
}
]}
What I'm trying to do here is a report on a simple survey submission data.我在这里尝试做的是一份关于简单调查提交数据的报告。 The question is "How did the users that answered 0 to the first question answer to the second question?"问题是“对第一个问题回答 0 的用户如何回答第二个问题?” I spent all day searching the SpringData Mongo Db docs but I found nothing.我花了一整天时间搜索 SpringData Mongo Db 文档,但一无所获。 Can anyone help?任何人都可以帮忙吗?
TIA TIA
You can workaround this issue by providing your own AggregationExpression
.您可以通过提供自己的AggregationExpression
来解决此问题。
ProjectionOperation agg = Aggregation.project() //
.and(new AggregationExpression() {
@Override
public DBObject toDbObject(AggregationOperationContext context) {
DBObject filterExpression = new BasicDBObject();
filterExpression.put("input", "$answer_list");
filterExpression.put("as", "answer");
filterExpression.put("cond", new BasicDBObject("$eq2", Arrays.<Object> asList("$$answer.question", 2)));
return new BasicDBObject("$filter", filterExpression);
}
}).as("profile");
There is one more alternative using Aggregation
还有一种使用Aggregation
替代方法
Aggregation aggregation = newAggregation(
project()
.and(filter("answer_list")
.as("answer")
.by(valueOf("answer.question").equalToValue(2)))
.as("profile"));
AggregationResults<OutputType> profile = mongoTemplate.aggregate(aggregation, InputType.class, OutputType.class);
I may not be able to answer your question correctly but I just wanted to give another approach for aggregation as there are lesser number of examples using Aggregation
.我可能无法正确回答您的问题,但我只想提供另一种聚合方法,因为使用Aggregation
的示例数量较少。
In project()
you can specify keys you want in your response, as its a varargs method在project()
您可以在响应中指定所需的键,作为可变参数方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.