Search code examples
c#.netmongodbmongodb-.net-driver

Mongodb C# driver throwing Element Name '_t' is not valid on UpdateOneAsync


I am getting MongoDb.Bson.SerializationException: 'Element name '_t' is not valid. I read all posts online that appear to be similar issue at first, however, in those posts, element name is specified, here, i am only getting '_t' even by trying different class objects.

        var database = AppConfig.client.GetDatabase("test");
        var collection = database.GetCollection<BsonDocument>("testcollection");

        var filter = Builders<Student>.Filter.Eq(g => g.Name, "oldName");
        

        var update = Builders<Student>.Update.Set(g => g.Name, "NewName");

        var updateResult = await collection.UpdateOneAsync(filter.ToBsonDocument(), update.ToBsonDocument());

Also, for all examples i have seen online for UpdateOneAsync function, filter and update below do NOT need to be BSON documents, however, my code won't compile unless I do .ToBSONDocument() as above.

var updateResult = await collection.UpdateOneAsync(filter, update);

My class is minimal:

    public class Student
    {
      [BsonElement("Name")]
      public string Name { get; set; }

      [BsonElement("Age")]
      public int Age { get; set; }
    
     }

Can someone please help figure out what is wrong with above?

Update: How to use render for Update.Set

        var registry = BsonSerializer.SerializerRegistry;
        var serializer = registry.GetSerializer<Student>();

        var filter = Builders<Student>.Filter.Eq(g=> g.Name, "NewName").Render(serializer, registry);

//I think update syntax is not correct.

        var update = Builders<Student>.Update.Set(g => g.Name, "Changed").Render(serializer, registry);


//update is throwing error:cannot convert from Mongodb.bson.bsonvalue to mongodb.Driver.updatedefinition<MongoDB.Bson.BsonDocument
            var updateResult = await collection.UpdateOneAsync(filter, update);

Solution

  • it's impossible to use ToBsonDocument as you did. The easiest fix is using not typed builders:

    var filter = Builders<BsonDocument>.Filter.Eq("name", "oldName");
    

    If you want to use typed builder, you should call Render as below:

            var registry = BsonSerializer.SerializerRegistry;
            var serializer = registry.GetSerializer<Student>();
            var filter = Builders<Student>.Filter.Eq(e=>e.Name, "oldName").Render(serializer, registry);