Search code examples
c#mongodbbson

Add field to a Mongo document using a string for its name


I'd like to create a new field on an existing document. I'm using the following line to get all the documents out of the database into POCOs:

var collection = _database.GetCollection<Address>(collectionName);

I then make some changes to each and save them back into the database using this line:

collection.ReplaceOne(
 filter: new BsonDocument("_id", a.id),
 options: new UpdateOptions { IsUpsert = true },
 replacement: a);

That all works nicely.

To add a field, I've tried the following:

a.ToBsonDocument().Add("RainfallMM", rainfallMM);

But it doesn't make it to the database. Is there a trick to it?


Solution

  • I asked you in comment did you add new property to address model and you said you didn't and you want to add it dynamically. Trick here is you initialize your collection as collection of addresses and mongo ignores all properties that are not part of address model by default.

    If you want to add it dynamically you need to change how you start your collection to:

    var collection = _database.GetCollection<BsonDocument>("addresses");
    

    Now your collection is not tied to address model and you can work with it as you wish. Everything is BSON document now!

    For example you can do this:

    var inserted = MongoCollection.Find(x => true).FirstOrDefault();
    inserted.Add(new BsonElement("RainfallMM", rainfallMM);
    MongoCollection.ReplaceOne(new BsonDocument("_id", inserted["_id"]), inserted);
    

    PS there are some other workarounds and if this one you don't like I can show you the rest =)

    Hope it helps! Cheers!