In the MongoDB driver for C#, I want to filter and then sort my collection with the following rules:
First: Sort the documents in descending order based on “toCompareDate” (which is not an actual field in the documents). “toCompareDate” is postedDate if postedDate is not null; otherwise, it is createdDate.
Second: If “toCompareDate” values are equal, prioritize the documents where postStatus is 4.
Can you help me with this?
Thank you so much!
I have tried the following:
public class Program
{
private static async Task Main(string[] args)
{
var client = new MongoClient("your_connection_string");
var database = client.GetDatabase("your_database_name");
var collection = database.GetCollection<Post>("Post");
int page = 1;
int limit = 10;
int skip = (page - 1) * limit;
var sortByStatus = new BsonDocument
{
{
"sortOrder", new BsonDocument
{
{ "$cond", new BsonArray
{
new BsonDocument("$eq", new BsonArray { "$PostStatus", 4 }),
1,
2
}
}
}
}
};
var pipeline = new[]
{
new BsonDocument("$addFields", sortByStatus),
new BsonDocument("$sort", new BsonDocument("sortOrder", 1)),
new BsonDocument("$skip", skip),
new BsonDocument("$limit", limit),
new BsonDocument("$project", new BsonDocument("sortOrder", 0))
};
var result = await collection.Aggregate<BsonDocument>(pipeline).ToListAsync();
foreach (var document in result)
{
Console.WriteLine(document);
}
}
}
But the result does not prioritize PostStatus 4.