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

标签 java spring mongodb spring-data-mongodb

我正在尝试使用 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 } }
]);

该集合具有以下结构:

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

我在这里想做的是一份关于简单调查提交数据的报告。问题是“第一个问题回答0的用户如何回答第二个问题?” 我花了一整天的时间搜索 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");

关于java - Spring Data MongoDb 是否支持 $filter 数组聚合运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39459898/

相关文章:

python - 如何编写数组值的匹配条件?

javascript - AngularJS - 客户有单独的 MongoDB 数据库

java - 在实例化时定义 Arraylist 的大小有什么好处吗

java - 使用 spring jdbctemplate 从数据库填充 pojo

SpringAMQP RabbitMQ如何在没有Exchange的情况下直接发送到队列

mongodb - mongodb 聚合中的 $replaceRoot

java - 用于计算英国邮政编码之间距离的库

java - 如何使用自定义参数配置提供程序?

java - 用于在 Java 中验证手机号码的正则表达式

在拦截器之前调用的 Spring Web MVC 3.1.1 参数解析器