Journeyman
Journeyman

Reputation: 10271

MongoDB sort order - mix of ascending and descending fields

I want to sort a MongoDB collection based upon several fields, some ascending, other descending. I'm using the official C# driver. My code currently looks like this:

string[] sortFields = new[] { "surname", "firstname","companyname","email" }; 
MongoDB.Driver.Builders.SortByBuilder sort = MongoDB.Driver.Builders.SortBy.Ascending(sortFields);
foreach (MongoDB.Bson.BsonDocument doc in contactsCollection.FindAs<MongoDB.Bson.BsonDocument>(query).SetSortOrder(sort))
{
...

How do I alter this code so it sorts on descending for email?

Thanks very much.

Upvotes: 4

Views: 5092

Answers (1)

mnemosyn
mnemosyn

Reputation: 46301

You can chain SortBy calls:

var sort = SortBy.Ascending("surname").Descending("email");
foreach (var doc in contactsCollection.FindAs<MongoDB.Bson.BsonDocument>(query).SetSortOrder(sort))
{
  ...

I'd be careful about building queries dynamically, especially with that many keys. Keep in mind that MongoDB uses only ONE index for a query, so your index will have to be a good fit.

Example: find({A: "foo", B: "bar"}).sort("C" : -1);

This won't use indexing efficiently if the compound index is {C, A, B}. It must be {A, B, C} instead. Too many indexes will take up space and make inserts / updates slower.

Upvotes: 7

Related Questions