Use REGEX to replace identical words in mongoDB

In my attempt to use mongosh in MongoDB, I am trying to replace all instances of selected words in a collection with others.

For example, if I have the following data:


_id:12345678901
name:"Peter Parker"
profession:"Superhero"

_id:12345678902
name:"Peter Parker"
profession:"Journalist"

_id:12345678902
name:"Hulk"
profession:"Software Developer"

I want to replace all occurrences of "Peter Parker" with "Superman" in a collection named "firstList", resulting in:


_id:12345678901
name:"Superman"
profession:"Superhero"

_id:12345678902
name:"Superman"
profession:"Journalist"

_id:12345678902
name:"Hulk"
profession:"Software Developer"

Even though I attempted the following code, it did not work as expected:


db.firstList.replace({
  "name": {
    "$regex": "/( |^)Peter Parker\b/g",
    "$replaceWith": "Superman"
  }
})

Answer №1

Based on the data at hand, there is no need to utilize regex. Simply use the word as is in the find stage.

To update using aggregation query and [], follow this format:

db.collection.update({
  "name": {
    "$regex": "Peter Parker"
  }
},
[
  {
    "$set": {
      "name": {
        "$replaceAll": {
          "input": "$name",
          "find": "Peter Parker",
          "replacement": "Superman"
        }
      }
    }
  }
],
{
  "multi": true
})

See an example here

If desired, you can still apply regex within the find object. However, for a precise match of "Peter Parker," regex may not be necessary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When verifying a MongoDB function, encountering a NameError for undefined variable 'db' is expected

I am encountering an issue with the assert_equal function, as it is stating that the name 'db' is not defined. The function in question is testing another function I wrote, which calculates the percentage of businesses with a rating value of 5. ...

Generate a text input field within a dropdown menu

Below is an example of my basic HTML code for a drop-down list: <span id="Div_List"> <label for="Gender">For:</label> <select name="Gender" id="Sex"> <option value="1">1000mtr</option> <option val ...

Using a jQuery UI dialog for multiple checkbox selection. The post array cannot be saved for a multi-select until the dialog is opened

CSS <td class="cell"> <a class="opener" id="opener_'.$iterator.'" href="#" rel="#type_dialog_<?= $iterator; ?>">Click here</a> <div id="type_dialog_<?= $iterator; ?>" name="t ...

Could there be an issue with the couch-nano changesReader batching, or am I overlooking something important?

This particular issue is related to the changesReader API within the couchdb-nano library. Expected Outcome In theory, the code below should wait for 10 seconds before returning a batch of messages from the most recent position in the changes feed. For in ...

Node.js appears to experience delays following successful connection to local MongoDB

I am encountering a problem while attempting to establish a connection to my MongoDB database and fetch data from it. After the connection is established, the terminal freezes, forcing me to interrupt the process using ctrl+C. Below is the code I am worki ...

Pattern matching for a text field that is optional, but must be validated if inputted into

My form includes a text box for a phone number with a versatile regular expression that can accommodate nearly all phone number variations, whether local or international. Here is the expression: ^((+)?[1-9]{1,2})?([-\s.])?(((\d{1,4}))|\d{1 ...

Confirm your email using a generated code through the integration of Node.js and MongoDB Atlas

In my current project, I am encountering an issue with Stack AT Mongodb. When a user receives a generated code and inputs it on the client side, the user document gets edited. However, the user is unable to log in because the bcrypt does not match or the u ...

Alter the cron schedule on-the-fly with a dynamic form

I am currently utilizing the Bull npm module to schedule jobs in Node.js. When it comes to repeating jobs, I want to be able to pass the value to cron through a form and update it dynamically. For instance, if I want a job to repeat every Monday to Frida ...

Avoid refreshing the page when adding an item to the cart

I am in the process of creating a online shopping cart and I'm looking for ways to avoid the page from reloading when adding a product to the cart. At the moment, my approach involves using the GET method to add products to the cart. <a href="car ...

When a button is clicked, an Internet Explorer security exception is triggered due to the security settings

My application allows users to select parameters for a PowerPoint report, run the report, and then save or open the file. I've managed to get all of that working smoothly. However, when the report is generated in a pop-up window and finished, using "w ...

Unable to include a fresh entry into an array (the value associated with a key) within a Mongoose schema

In my mongoose schema named users, there is a field called likes. Whenever a user likes another user's post, the userId of the liker is added to the likes array. router.put("/:id/like", async (req, res) => { try { const post = await Post.f ...

The issue I am facing is that the map function is not functioning correctly when I click

I am currently working on a project in ReactJs that includes a sidebar with dropdown menu functionality. Desired Outcome When I click on an option in the sidebar that has a submenu, it should display that submenu and close upon another click. Curr ...

implementing a three-tiered nested URL structure in Angular

My app.js code snippet: .state('dashboard', { url: '/dashboard', templateUrl : 'resources/components/dashboard/dashboard.html', controller : 'dashboardController', }) ...

Removing event notifications with Google Calendar API v3 (JavaScript): A Step-by-Step Guide

After creating a JSON object with event details, I attempted to add it to Google Calendar using the provided code snippet: function addEvent() { gapi.client.load('calendar', 'v3', function() { var request = gapi.client.calendar.e ...

Tips for setting up a jQuery auto-suggest feature that fetches both the value and ID

Looking for a solution similar to an auto-complete feature, where a user can select from options already in a database or add new entries if not found. The goal is to retrieve the ID, send it to PHP, and check if it already exists. If not, a new entry shou ...

I just made an ajax call. Now, how should I proceed with formatting the data that was returned

The ajax request below is functional, but not without its challenges. Working with HttpContext has proven to be difficult, as even Context.Response.Clear() does not seem to have any effect. How can I output only the desired content without any extra infor ...

django.core.exceptions.ImproperlyConfigured: the specified name should be an object of type basestring

I'm currently attempting to integrate Mongodb into my Django project. Below are the connection settings specified in settings.py DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '<a href="/cdn-cgi/l/email-protect ...

What is the connection between {{result}} and $scope.result within AngularJS?

I comprehend the concept of binding a model to an element. An example would be... <pre ng-model="result">. This connection is established through the $scope.result variable. However, how are these two related? {{result}} $scope.result = data; ...

Displaying selected values in a Multi Select Listbox upon submission of the same form when an error occurs

When the page is first loaded: Retrieve the values from the table field and store them in a variable If the field is blank, do not take any action Populate the listbox with default custom values When the form is submitted (on the same page) and multipl ...

Exploring the world of Django, JavaScript, and intricate form designs

I am currently developing an application in django that allows users to create and modify flowcharts for process/procedure control. The app consists of three main models: Procedure, Step, and Transition. All the model relationships have been established a ...