Uploaded image for project: 'Java Driver'
  1. Java Driver
  2. JAVA-2235

Multiple $match filters in BSON for aggregator

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Critical - P2 Critical - P2
    • None
    • Affects Version/s: 3.2.2
    • Component/s: API, BSON
    • Labels:
    • Environment:
      Java 1.8, Java MongoDB driver v3.2.2, MongoDB 3.0.11

      I'm running with below aggregation where in match condition will be added depending upon selected filter
      Bson detailsUnwind = unwind("$details");

      Bson empIdMatch = new BasicDBObject();
      Bson deptIdMatch = new BasicDBObject();
      Bson gradeMatch = new BasicDBObject();

      empIdMatch = match(eq("empId",1234567)); // mandatory value - empId
      if(deptId != null) // optional value - deptId
      deptIdMatch = match(eq("details.deptId",20));
      if(grade != null) // optional value - grade
      gradeMatch = match(eq("details.grade","L1"));

      List<Bson> pipeline = asList(detailsUnwind,empIdMatch,deptIdMatch,gradeMatch);

      AggregateIterable<Document> aggresult = collection.aggregate(pipeline);

      for (Document documet : aggresult) {
      Document doc = (Document) documet.get("details");
      if (doc != null)

      { System.out.println("Testing"); }

      }

      If i level is not available, than i'm getting -
      Command failed with error 16435: 'exception: A pipeline stage specification object must contain exactly one field.' on server <hostname>:<port>. The full response is

      { "code" : 16435, "ok" : 0.0, "errmsg" : "exception: A pipeline stage specification object must contain exactly one field." }

      This is what i want to achieve

      Case 1) When both Department and Level details are available
      collection.aggregate(
      [
      {$unwind: '$details'},
      { $match:
      {'empId': 123456,
      'details.deptId' : 20,
      'details.grade' : 'L1'
      }}
      ]
      )

      Case 2) When only Grade is available
      collection.aggregate(
      [
      {$unwind: '$details'},
      { $match:
      {'empId': 123456,
      'details.grade' : 'L1'
      }}
      ]
      )

            Assignee:
            Unassigned Unassigned
            Reporter:
            paddyrec PRDP
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: