C# .NET MongoDB Replace string using $replaceOne

Replace Substring in MongoDB document shell C NET MongoDB Replace string using $replaceOne

Today this article will learn to write a query using C# .NET MongoDB Replace string using $replaceOne aggregation example.

We will replace a string in the Mongo document with the input string using a simple and easy approach i.e using $replaceOne aggregation operator.

We will cover below aspects,

 

We will update the records using the Mongo shell query.

We already looked at a simple way of adding or updating a new field to the document in our previous MongoDB sample series.

Getting started

Please add the MongoDB driver NuGet package using the Nuget Package manager.

PM> Install-Package MongoDB.Driver -Version <version>

Note – Please use the latest version available.

Step I – Establish the connection with the MongoDB driver

var _mongoClient = new MongoClient("mongodb://your connection string"); 

var db = _mongoClient.GetDatabase("TheCodeBuzz");

Step II – Get the collection object for the given Mongo Database

var collection = db.GetCollection("Orders");

Here below is a sample schema or document we shall use,

C NET MongoDB Replace string


C#.NET – Replace Substring in MongoDB using $replaceOne Aggregator

We are going to use a newly introduced aggregate operator to replace easily a string with matching criteria with part of the string.

What is $replaceOne

$replaceOne is aggregation operator which helps replace the first instance of a search string in an input string with a replacement string.

This operator usage is case-sensitive.

Query Pattern Replace using $replaceOne

{ 
 $replaceOne: { 
    input: <expression>, 
    find: <expression>, 
    replacement: <expression>}
}

In the above query,

inputInput string with search criteria.
findFind the document with matching input string criteria.
replacementThe string to use to replace the first matched instance from input

You can replace the existing Mongo field using any other fields from the document using the above approach + using the approach discussed here.

Example using $replaceOne

In the below example, we will replace “total-order” with “order” in the mongo field.

Add below using the required for MognoDB query execution,

using MongoDB.Bson;
using MongoDB.Driver;
using System.Text.RegularExpressions;

Mongo Filter Query

Below query filter all the records with the “Link” field value matching with the “total-order” value.

var filter = new BsonDocument("Link", new BsonDocument("$regex", new Regex("total-order")));

MongoDB C# $replaceOne Query

Below represent a C# representation of the aggregation query,

var query = new BsonDocument("Link", new BsonDocument("$regex", new Regex("total-order"))),new BsonArray
{
    new BsonDocument("$set", 
    new BsonDocument("Link", 
    new BsonDocument("$replaceOne", 
    new BsonDocument
                {
                    { "input", "$Link" }, 
                    { "find", "total-order" }, 
                    { "replacement", "order" }
                })))
}

Complete the sample as below,

_mongoClient = new MongoClient(connectionString);

 
var db = _mongoClient.GetDatabase("TheCodeBuzz");

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

 var filter = new BsonDocument("Link", new BsonDocument("$regex", new Regex("total-order")));

            BsonDocument doc = new BsonDocument();

            var stageBson=  new BsonDocument
            {
                new BsonDocument("$set",
                new BsonDocument("Link",
                new BsonDocument("$replaceOne",
                new BsonDocument
                            {
                                { "input", "$Link" },
                                { "find", "total-order" },
                                { "replacement", "order" }
                            })))
            };
            doc.AddRange(stageBson);


          

Create Update Pipeline

Below is how you can create an update pipeline instance as below.

Create Pipeline for $replaceOne
image 1 C NET MongoDB Replace string using $replaceOne

Below is the document post replacing the value of fields.

C $replaceOne example

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 *