Spring mongo aggregation filter with $and, $in and $eq conditions
Asked Answered
D

1

0
{
 "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.

Darien answered 30/12, 2019 at 17:35 Comment(0)
B
2

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");
Bursiform answered 31/12, 2019 at 6:28 Comment(1)
In the last line should be '.as("Field2");'Unaccompanied

© 2022 - 2024 — McMap. All rights reserved.