Spring Data MongoDb 是否支持 $filter 数组聚合运算符?

Does Spring Data MongoDb support $filter array aggregations operator?

我正在尝试在 Spring 数据中实施 Mongo 模板以下工作 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 } }
]);

该集合具有以下结构:

{
"_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)
    }
]}

我在这里要做的是一份关于简单调查提交数据的报告。问题是 "How did the users that answered 0 to the first question answer to the second question?" 我花了一整天时间搜索 SpringData Mongo Db 文档,但一无所获。 有人可以帮忙吗?

TIA

您可以通过提供自己的 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");

还有一种选择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);

我可能无法正确回答您的问题,但我只是想提供另一种聚合方法,因为使用 Aggregation.

的示例数量较少

project() 中,您可以在响应中指定所需的键,因为它是一个可变参数方法