Spring mongo aggregation filter with $and, $in and $eq conditions

和自甴很熟 提交于 2020-01-10 06:11:06

问题


{
 "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:


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");


来源:https://stackoverflow.com/questions/59534705/spring-mongo-aggregation-filter-with-and-in-and-eq-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!