Suppose you want to retrieve a bunch of documents that have a timestamp field from a Mongo database using the C# driver, and you want them sorted by timestamp in decreasing order (-1).
When creating an index, do you need to include the timestamp field in the -1 order, for the queries that sort this way? Or is it unnecessary because sorting will only occur once the documents have been extracted from the Mongodb and converted to C# objects, and thus sorted "in-memory" by .NET?
Suppose my documents have the fields: user_id, action_id, and timestamp
I want to have an index that will aid the search for all actions for a user, and sorted in decreasing order. Should my index include just user_id and action_id, or should it also use the timestamp field?
Accodring to the docs, the Mongo driver contains a LINQ implementation targeting the Mongo aggregation framework. That means a query like
var query = from p in collection.AsQueryable()
orderby p.Name, p.Age descending
select p;
//or
var query = collection.AsQueryable()
.OrderBy(p => p.Name)
.ThenByDescending(p => p.Age);
would map into the following aggregation pipeline:
[
{ $sort: { Name: 1, Age: -1 } },
]
Of course you don't have to use LINQ, you can also write equivalent queries without it. But the answer is that yes, the driver does support converting your queries into something executed on the DB side.
This page in the docs refers I believe to the exact situation you're describing:
db.records.createIndex( { a: 1 } )
would support both in-order and reverse-order traversal:
db.records.find().sort( { a: 1 } )
db.records.find().sort( { a: -1 } )
The docs have plenty of information on indexes so I recommend you read up on them to get a feeling of what's best for your use case.