title: Why is my .NET MongoDb Driver Query Horribly Slow?
body: <p>I run a query to <code>select all items where field1=x, field2 =y, and field3=z</code> directly in Mongo (Robomongo, CLI, whatever) and it takes less than a second on several hundred thousand items:</p>
  
  <pre><code>db.items.find( { 
      $and: [ 
          { CreatingOrgId: 1 }, 
          { LocationId: 941 },
          { StatusId: 1}
      ] 
  } )
  </code></pre>
  
  <p>I then try to run the exact same thing from C# driver and it lags out(only "Aggregate filter" code is relevant, everything else is for context):</p>
  
  <pre><code>FilterDefinition&lt;BsonDocument&gt; locationsFilter;  = Builders&lt;BsonDocument&gt;.Filter.Eq("LocationId", 941);
  FilterDefinition&lt;BsonDocument&gt; orgFilter = Builders&lt;BsonDocument&gt;.Filter.Eq("CreatingOrgId", 1);
  FilterDefinition&lt;BsonDocument&gt; statusFilter = Builders&lt;BsonDocument&gt;.Filter.Eq("StatusId", 1);
  
  FilterDefinition&lt;BsonDocument&gt; aggregateFilter = locationsFilter &amp; statusFilter &amp; orgFilter;
  
          List&lt;ItemViewModel&gt; stuffList = mongoItemsCollection
                                               .Find(aggregateFilter)
                                               .Project(x =&gt; Mapper.Map&lt;BsonDocument, StuffViewModel&gt;(x))
                                               .ToListAsync().Result;
  </code></pre>
  
  <p>What's my mistake here? Here are the queries as mongo sees them:</p>
  
  <p><a href="https://i.stack.imgur.com/mqEsV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mqEsV.png" alt="enter image description here"></a></p>
  
  <p>Edit: Looks like mapping the items to item object is what's killing my query to some degree. It's fairly fast (couple of seconds for a huge number of records) without the mapping, like so:</p>
  
  <pre><code>    var rawItems = mongoItemsCollection
                               .Find(aggregateFilter)
                               .ToListAsync().Result;
  </code></pre>
  
  <p>Edit 2: Looks like automapper is a HUGE part of the problem here (taking the bson "item" object and converting it to a .NET view model). I am still interested in optimization of the .NET --> mongo query itself though (ignoring the automapper part), if anyone wants to answer. </p>