How to parse a JSON array in C#?

c#, mongodb-.net-driver

Solution

Not a bad idea if that suits your purposes. Yes the C# driver already supports BSON serialization from a JSON string source:

string json = '[
    { "$match: { "foo": "bar" } },
    { "$group": {
        "_id": null, 
        "count": { "$sum": 1 }
    }}
]';

BsonDocument pipeline = 
    MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonArray>(json);

So you can pull in your aggregation pipeline strings formatted as JSON and use them or manipulate them as BSON documents.

Problem

Using the MongoDB C# driver how can I parse a JSON array (string) into `BsonDocument[]`? We would like to store our mongo aggregation pipelines in separate JSON documents so need a way to parse them.

Original source