MongoDB C# .NET – Add a new field to document in MongoDB Collection using UpdateMany

Add a new field to document in MongoDB Collection

Today in this article will see how to add a new field to document in MongoDB programmatically using C# MongoDB driver in .NET or .NET Core application.

We will also see how to add a new field to the document in MongoDB collection using the command line argument.

Today in this article, we will cover below aspects,

Please visit the below article for criteria-based Updates/Add to an existing document in MongoDB.

Getting started

Please create any .NET/.NET Core application.

Add MongoDB Nuget packages

Please add the MongoDB driver NuGet package using the Nuget Package manager or CLI commands

PM> Install-Package MongoDB.Driver -Version 2.9.3

Again, I shall keep the Mongo driver interface use simple here to concentrate on how to add new fields to existing documents.

Please visit for better approaches like using DI or IoC here,

Step I – Establish the connection with MongoDB driver,

var _mongoClient = new MongoClient("mongodb://your connection string");
var db = _mongoClient.GetDatabase("Book");

Step II – Get all the records from the given collection,

More Typesafe way

IMongoCollection<Book> collection = db.GetCollection<Book>("Book");

Or

Generic way

  var collection = db.GetCollection<BsonDocument>("Book");

Note: Discussed logic will load the full database. If you need to implement batches or chunk update asynchronously, please visit the below article,

Use the UpdateMany extension method of collection to add the required new field.

Below are the MongoDB documents before adding the new field.

Step III – Let’s add a new field “BookStore” to the existing document,

More Typesafe way

Generic way using BsonDocument

blank

We are using the UpdateMany command which lets you perform a bulk update for the given FilterDefinition or UpdateDefinition defined.

blank

Above we use Upsert commands which will create a new entry if doesn’t exist. Else it will do a normal update.

That’s all!

Please visit the below article for criteria-based Updates/Add to an existing document in MongoDB.

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *