Search code examples
c#mongodblambdamongodb-.net-driver

Ensure utilization of compound index with lambda


We query a schools collection by two fields using the mongocsharpdriver (v2.0.0) API like:

db.GetCollection<School>("schools").Find(x => x.City == myCity && x.State == myState);

Will the order of the fields listed in the lambda expression generate a query to leverage a compound index with the same order: { "city": 1, "state": 1 }?

I'm fairly new to mongodb, but if I understand correctly, we could create a second (reversed) compound index: { "state": 1, "city": 1 } to ensure one of them is used. I'm just more interested how the lambda is translated and couldn't find what I was looking for in mongodb's documentation.


Solution

  • The order in which your query is built, whether by typing in json explicitly or generating it from a lambda expression has no effect on the index selection.

    When you have a compound index in MongoDB the order of the properties in the index matters but the order in the query doesn't.

    Your index, { "city": 1, "state": 1 }, can satisfy both of these queries exactly the same:

    db.GetCollection<School>("schools").Find(x => x.City == myCity && x.State == myState);
    db.GetCollection<School>("schools").Find(x => x.State == myState && x.City == myCity);
    

    The difference comes when you use a single property so this:

    db.GetCollection<School>("schools").Find(x => x.City == myCity);
    

    Works better with your index than this:

    db.GetCollection<School>("schools").Find(x => x.State == myState);
    

    More in MongoDB : Indexes order and query order must match?