Journeyman
Journeyman

Reputation: 10271

MongoDB sort BsonArray

In C#, if I have a BsonArray of BsonDocuments and I want to sort the BsonArray elements based upon an element within each BsonDocument, how do I do it?

Something like this:

BsonArray originalTags = doc["tags"].AsBsonArray;
BsonArray newTags = originalTags.OrderBy(what goes here?);

I'm using this to sort nested documents, so I can't use the collection sort methods. I'm using the official C# driver.

Upvotes: 1

Views: 2206

Answers (1)

Robert Stam
Robert Stam

Reputation: 12187

OrderBy is an extension method from LINQ (not the C# driver), and it has two overloads. In one you provide a lambda to extract the key you want to sort on, and in the other you additionally provide a lambda that compares two keys.

Here's an example that sorts a BsonArray based on the value of an embedded element called "x":

var originalTags = new BsonArray {
    new BsonDocument { { "_id", 1 }, { "x", 2 } },
    new BsonDocument { { "_id", 2 }, { "x", 1 } }
};
var newTags = originalTags.OrderBy(t => t.AsBsonDocument["x"]);

foreach (var tag in newTags) {
    Console.WriteLine(tag.ToJson());
}

Upvotes: 2

Related Questions