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.
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.
The accepted answer's result is a BsonArray, if you need a BsonDocument[]
you'll do something like
BsonSerializer.Deserialize<BsonArray>(yourJsonString).Select(p => p.AsBsonDocument)
and if you need it as a List<BsonDocument>
BsonSerializer.Deserialize<BsonArray>(yourJsonString).Select(p => p.AsBsonDocument).ToList<BsonDocument>()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With