MongoDB Rename field using .NET C#
Today this article will see how to perform MongoDB rename field using .NET C# programmatically using MongoDB driver.
We will also see how to add a rename field to the document in MongoDB collection using the command line argument.
Today in this article, we will cover below aspects,
visit the below article for criteria-based Updates/Add to an existing document in MongoDB,
Getting started
Please create any .NET/.NET Core application.
Please add the MongoDB driver NuGet package using the Nuget Package manager.
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 rename fields from existing documents.
Please visit for better approaches like using DI or IoC here,
Step I – Establish the connection with the 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.
var collection = db.GetCollection("employee");
Note: Below logic will load the full database. If you need to implement batches or chunk updates asynchronously, please visit the below article,
Below are the MongoDB documents before renaming the new field.
I have below Mongo Collection where my fields are defined as below.
I have a field name called “EmpID” which I want to rename to “EmpNumber”
Step III – Let’s rename the fields.
Command Pattern
{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }
Generic way using BsonDocument
foreach (var rootObject in documents) { var update = Builders<BsonDocument>.Update.Rename("EmpID", "EmpNumber"); var filter = Builders<BsonDocument>.Filter.Eq("_id", (ObjectId)rootObject.GetElement("_id").Value); var options = new UpdateOptions { IsUpsert = true }; collection.UpdateOne(filter, update, options); }
We are using the UpdateOne command which lets you perform updates for each record using “_id” as filter criteria.
Asynchronous Rename operation
You can use UpdateOneAsync.
await collection.UpdateOneAsync(filter, update, options);
One can also try using UpdateMany for bulk updates of string.
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
References:
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.