Home > database >  Creating MongoDB like update document in C#
Creating MongoDB like update document in C#

Time:01-07

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?

CodePudding user response:

This should work:

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

This will render the Update document to a BsonValue.

  • Related