1

I am trying to create a MongoDB like update document in my C# code. This is not used to update the MongoDB but the API I am using expects the data in this format.

I tried using MongoDB.Driver NuGet package and tried to create the document like this.

class Program
{
    class MyTest
    {
        public string Name { get; set; } = String.Empty;
        public string Description { get; set; } = String.Empty;
    }

    public static void Main()
    {
        var v = Builders<MyTest>.Update
            .Set(t => t.Name , "TestName")
            .Set(t => t.Description ,"TestDescription");

    }
}

This code compiles and runs. But I need the output in string format. Something like:

$set: {Name:"TestName",Description:"TestDescription"}

Is there anyway to get a string representation like that?

1

1 Answer 1

1

This should work:

var output = v.Render(BsonSerializer.LookupSerializer<MyTest>(), new BsonSerializerRegistry());

This will render the Update document to a BsonValue.

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

4 Comments

better to do the following: var registry = BsonSerializer.SerializerRegistry; var serializer = registry.GetSerializer<MyTest>(); var rendered = v.Render(serializer, registry);
@dododo LookupSerializer() method does exactly what you wrote.
Awesome..works as expected.
@RaduHatos, no, it doesn't. In your case, you ignore predefined serializers

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.