7

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.

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Which version of the driver? this doesn't compile for me using the 2.x C# driver. It says it can't implicitly convert BsonArray to BsonDocument. Explicit casting isn't allowed either.
ten years later... I just obtained proof that it works with C# driver version 2.25.0
10

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>()

1 Comment

This should be the correct answer. The first one returns a BsonArray, whether this returns a collection of BsonDocument as asked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.