Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-35223

$elemMatch forces mongo to fetch documents instead of using COUNT_SCAN

    • Type: Icon: Bug Bug
    • Resolution: Works as Designed
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 3.4.15
    • Component/s: Querying
    • Labels:
      None
    • ALL

      When perform "count" with "$elemmatch" in the query it never uses COUNT_SCAN and has to FETCH document before counting. Here is an example:

      //create a simple document that has an array of embedded doc, like this:
      var doc = {
          "annotationList": [
              {
                  "meta": {
                      "league": "league_value1",
      				"class": "class_value1"
                  }
              },
              {
                  "meta": {
                      "league": "league_value1",
      				"class": "class_value1"
                  }
              }
          ]
      }
      
      //save doc to the collection
      db.testCollection.save(doc);
      
      
      //build compound index using 2 multikey field
      db.testCollection.ensureIndex({"annotationList.meta.league": 1, "annotationList.meta.league": 1});

      Now if we perform the following:

       

      db.testCollection.explain("executionStats").count({
      	
      	"annotationList": {
      		"$elemMatch": {
      			"meta.league": "league_value1"
      		}
      	}
      	
      });

      We can see that it does the following: XSCAN -> FETCH -> COUNT

      However if we do the following:

      cursor = db.testCollection.explain("executionStats").count({
      	
      	"annotationList.meta.league": "league_value1"
      
      });
      

       

      We can see that now there is not need to FETCH documents and it simply performs COUNT_SCAN

       

       

            Assignee:
            asya.kamsky@mongodb.com Asya Kamsky
            Reporter:
            ASemen Alexey [X]
            Votes:
            1 Vote for this issue
            Watchers:
            11 Start watching this issue

              Created:
              Updated:
              Resolved: