Search code examples
mongodbmongodb-.net-driver

AddToSetEach operator won't return the correct query (Builders v 2.4.4)


I've some code to update an array (add to set). The code is currently using the legacy builder:

var data = new[] { 10, 20, 30 };
var fieldName = "data";

var oldWay = Update.AddToSetEach(fieldName , new BsonArray(data));
Console.WriteLine($"Old way:\n {oldWay.ToJson()} \n\n");

This works perfectly and prints:

Old way:
 { "$addToSet" : { "users" : { "$each" : [10, 20, 30] } } }

But when trying to use the new Builders class, I can't get it to work correctly. I'm using MongoDB.Driver 2.4.4. My code:

var data = new[] { 10, 20, 30 };
var fieldName = "data";

var newWay = Builders<BsonDocument>.Update.AddToSetEach(fieldName, new BsonArray(data)).ToJson();
Console.WriteLine($"New way:\n {newWay} \n\n");

The output is:

New way:
 { "_t" : "AddToSetUpdateDefinition`2" }

Any thoughts?

Thank you!


Solution

  • I don't think .ToJson() renders the string how you want it to on a FilterDefinition. It used to be a little easier in the old driver.

    Someone wrote an extension method though:

    public static class MongoExtensions
    {
        public static BsonDocument RenderToBsonDocument<T>(this UpdateDefinition<T> filter)
        {
            var serializerRegistry = BsonSerializer.SerializerRegistry;
            var documentSerializer = serializerRegistry.GetSerializer<T>();
            return filter.Render(documentSerializer, serializerRegistry);
        }
    }
    

    Then you can

    var data = new[] { 10, 20, 30 };
    var fieldName = "data";
    
    var newWay = Builders<BsonDocument>.Update.AddToSetEach(fieldName, new BsonArray(data));
    
    var newWayJson = newWay .RenderToBsonDocument().ToJson();
    
    Console.WriteLine($"New way:\n {newWayJson } \n\n");