Pymongo – Replace Substring in Document using Python example

python replace string mongodb pymongo Python MongoDB Replace String in Pymongo with example

Today this article will learn to write query using Python MongoDB – Replace String in Pymongo with 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 using Pymongo driver code.

We will cover below aspects,

 

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 – Pymongo

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

Python MongoDB Replace String in Pymongo with example



Python Replace Substring in MongoDB – $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.

PyMongo- Query Pattern 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.

Pymongo Replace String

Please add below using the namespace in your code,

import re

from pymongo import MongoClient

For more details on Pymongo installation and details, please visit https://api.mongodb.com/python/current

Define PyMongo Replace query

Let’s define the filter using $replaceOne as below,

filter= {
    'Link': {
        '$regex': re.compile(r"total-order")
    }
},[
    {
        '$set': {
            'Link': {
                '$replaceOne': {
                    'input': '$Link', 
                    'find': 'total-order', 
                    'replacement': 'order'
                }
            }
        }
    }
]

Above we are defining regex to find all the document where string matches with “total-order”.

This match will filter only records with matching criteria and hence fasten the search.

Below is the complete code with example?

import re
from pymongo import MongoClient

client = MongoClient('your connection string')

filter= {
    'Link': {
        '$regex': re.compile(r"total-order")
    }
},[
    {
        '$set': {
            'Link': {
                '$replaceOne': {
                    'input': '$Link', 
                    'find': 'total-order', 
                    'replacement': 'order'
                }
            }
        }
    }
]

result = client['TheCodeBuzz']['Orders'].find(
  filter=filter
)



Below is the schema post-update,

Python Replace Substring in MongoDB


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 *