Spring mongo aggregation filter with $and, $in and

2020-02-16 03:36发布

{
 "Field1": "ABC",
 "Field2": [
    { "Field3": "ABC1","Field4": "REVIEWED","Field5":"True" }, 
    { "Field3": "ABC2","Field4": "APPROVED","Field5":"True" }, 
    { "Field3": "ABC3","Field4": "REJECTED","Field5":"True" }, 
    { "Field3": "ABC4","Field4": "APPROVED","Field5":"False" } 
    ]
}

I want to fetch APPROVED,REVIEWED and True record ie.

{
 "Field1": "ABC",
 "Field2": [
    { "Field3": "ABC1","Field4": "REVIEWED","Field5":"True" }, 
    { "Field3": "ABC2","Field4": "APPROVED","Field5":"True" }
    ]
}

following mongo aggregation query returns proper result

{
  "$project": {
    "Field1": "$Field1",
    "Field2": {
      "$filter": {
        "input": "$field2",
        "as": "fld2",
        "cond": {
          "$and": [
            {
              "$in": [
                "$$fld2.field4",
                [
                  "APPROVED",
                  "REVIEWED"
                ]
              ]
            },
            {
              "$eq": [
                "$$fld2.field5",
                "True"
              ]
            }
          ]
        }
      }
    }
  }
}

how to achieve the above query in spring mongo data db? Spring ProjectOperation with ArrayOperators.Filter.filter not providing chaining operation to do and with another condition.

1条回答
倾城 Initia
2楼-- · 2020-02-16 03:59

You can try using BasicDBObject like this

 BasicDBObject inOp = new BasicDBObject("$in", Arrays.<Object>asList(
                        "$$fld2.field4",
                        Arrays.asList("APPROVED","REVIEWED")));

  BasicDBObject eqOp = new BasicDBObject("$eq", Arrays.<Object>asList(
                        "$$fld2.field5",
                       "True"));

 BasicDBObject andOp = new BasicDBObject("$and", Arrays.<Object>asList(inOp, eqOp));

 project("Field1")
 .and(new AggregationExpression() {
              @Override
              public DBObject toDbObject(AggregationOperationContext aggregationOperationContext) {
                DBObject filterExpression = new BasicDBObject();
                filterExpression.put("input","$field2");
                filterExpression.put("as", "fld2");
                filterExpression.put("cond",andOp);
                return new BasicDBObject("$filter", filterExpression);
              }
            }).as("Field2");
查看更多
登录 后发表回答