Does Spring Data MongoDb support $filter array aggregations operator?

前端 未结 2 1984
失恋的感觉
失恋的感觉 2020-12-22 08:29

I\'m trying to implement in Spring Data using MongoTemplate the following working mongoDb query:

db.answers.aggregate([
        { \"$match\" : { \"object_id\         


        
相关标签:
2条回答
  • 2020-12-22 09:08

    You can workaround this issue by providing your own 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");
    
    0 讨论(0)
  • 2020-12-22 09:23

    There is one more alternative using 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.

    In project() you can specify keys you want in your response, as its a varargs method

    0 讨论(0)
提交回复
热议问题