Delete any fields that start with the name "XX"

Here is an example document extracted from a collection:

{ "teamAlpha": { }, "teamBeta": { }, "leader_name": "leader" }

My goal is to remove all fields that begin with "team" from this document. Therefore, the expected outcome would be:

{leader_name: "leader"}

In order to achieve this, I am currently employing the following function:

db.teamList.find().forEach(
    function(document) {
        for(var k in document) {
            if (k.startsWith('team')) {
                delete document[k];
            }
        }
        db.teamList.save(document);
    }
);

I am curious if there exists a more efficient solution to this issue.

Answer №1

To optimize the process, it is recommended to identify all potential keys in advance and then execute a single update command using the multi-parameter to eliminate all identified keys. The methodology may vary depending on the version of MongoDB being used.

Approach for MongoDB 3.4: $objectToArray

let fields = db.teamList.aggregate([
  { "$project": {
    "_id": 0,
    "fields": {
      "$map": {
        "input": {
          "$filter": {
            "input": { "$objectToArray": "$$ROOT" },
            "as": "d",
            "cond": { "$eq": [{ "$substrCP": [ "$$d.k", 0, 4 ] }, "team" ] }
          }
        },
        "as": "f",
        "in": "$$f.k"
      }
    }
  }},
  { "$unwind": "$fields" },
  { "$group": { "_id": "$fields" } }
])
.map( d => ({ [d._id]: "" }))
.reduce((acc,curr) => Object.assign(acc,curr),{})

db.teamList.updateMany({},{ "$unset": fields });

The aggregate() function transforms the document fields into an array using $objectToArray, filters out only the ones with keys starting with "team", and then generates a unique list of these matching fields through unwind and group operations.

The subsequent steps convert this list into a single object and utilize $unset to remove these fields from all documents.

For Earlier Versions: mapReduce

var fields = db.teamList.mapReduce(
  function() {
    Object.keys(this).filter( k => /^team/.test(k) )
      .forEach( k => emit(k,1) );
  },
  function() {},
  { "out": { "inline": 1 } }
)
.results.map( d => ({ [d._id]: "" }))
.reduce((acc,curr) => Object.assign(acc,curr),{})  

db.teamList.update({},{ "$unset": fields },{ "multi": true });

A similar approach is used, with the only distinction being the utilization of update() instead of updateMany() for versions lacking the latter method, specifying the "multi" parameter to affect all matched documents.

Advanced Options

Exhausting all documents just to delete fields is not recommended. Therefore, the aforementioned methods are preferred. However, constructing an extensive list of keys might surpass the 16MB BSON limit in rare cases.

Two potential extensions to the techniques include using the cursor with aggregate() to process fields in batches and creating a temporary collection with mapReduce() to iteratively handle distinct field names.

If you are aware of all the field names in advance, you can directly specify them in the update statement without the need for elaborate calculations.

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

Using jQuery and Laravel framework to handle a POST request

Could someone assist me with troubleshooting a jQuery post request issue? I suspect there may be an error with the routes or controller. Here is my JavaScript code for the post request: $.post('http://localhost:8000/ajax', { ...

Modify the URL parameter when a button is clicked

I want to apologize in advance for not providing more information. If the limited info is not enough, I will remove the question. There's a script that creates a search engine based on another dynamically generated script which is complex and beyond ...

Restful Spinner

app.config(function(RestangularProvider) { RestangularProvider.addRequestInterceptor(function(element) { console.log("Request initiated"); return element; }); RestangularProvider.addResponseInterceptor(function(data) { ...

Is it possible to center-align the text in a Material-ui TextField and enforce a minimum numerical value at the same time?

I'm facing an issue with trying to center align the text inside the TextField and also set a minimum value of 0. It seems like I can only achieve one or the other, but not both simultaneously. I referred to the material-ui page on TextField for help, ...

Tips for preventing circular dependencies in JavaScript/TypeScript

How can one effectively avoid circular dependencies? This issue has been encountered in JavaScript, but it can also arise in other programming languages. For instance, there is a module called translationService.ts where upon changing the locale, settings ...

"I'm curious about how to reset a form in reactjs hooks after it has been submitted

Just dipped my toes into the world of hooks and I'm stumped on how to clear input fields post-submit. Tried form.reset() but it's not doing the trick. import { useForm } from "react-hook-form"; import.... export default function AddUse ...

Transmitting data from the front end to the server in React/Shopify for updating API information using a PUT request

After successfully retrieving my API data, I am now tasked with updating it. Within my component, I have the ability to log the data using the following code snippet. In my application, there is an input field where I can enter a new name for my product an ...

The PHP file on the server is missing the mandatory "event" parameter for the EventSource

Explaining this issue was a bit of a challenge. I've set up a Javascript EventSource object with some customized event handlers like so: var source = new EventSource('updates.php'); source.addEventListener('add', addHandler, fals ...

Combining Rxjs map and filter to extract countries and their corresponding states from a JSON dataset

I have a unique dataset in JSON format that includes information about countries and states. For example: { "countries": [ { "id": 1, "name": "United States" }, { "id": 2, "name": "India" }], "states": [ { ...

Obtain the names of the cities that the Google Maps route passes through

Currently working on a website that integrates Google Map API v3. Is there a method to gather the names of the places or cities along the route from point A to B? The page utilizes JavaScript for functionality. ...

Use jquery ajax to upload an image with a reusable input field

UPDATE: Progress has been made in solving this issue. Please refer to Jquery form no submission to IE7 and IE8. The main task remaining is sorting out the compatibility with IE7 and IE8. I have been utilizing THIS plugin to upload files as email attachmen ...

Button to close Jquery Dialog

I've set up a custom alert UI using jQuery UI, but I'm having trouble getting the close button to work properly. Here's my code snippet where I'm trying to override the default alert() function with jQuery UI dialog as described in this ...

Easily use Discord.JS 13 slash commands to generate an embed displaying a user's specific role within a server

Currently, I am in the process of creating a slash command that will reveal a user's specific roles when the command is triggered. run: async (client, interaction) => { try{ const { member, channelId, guildId, applicationId, comman ...

Encountered an issue while attempting to send a POST request using AngularJS $

I am facing an issue with accessing the POST method from my server. Whenever I log the response, it always returns status=0. Can anyone help me out or provide some advice? Note: I have tested the method in Postman and it works fine. Below is the code snip ...

What is the process for implementing text box validation on a button click within a gridview in asp.net utilizing javascript?

How can I implement textbox blank validation on button click within a gridview using JavaScript? My gridview has multiple rows with 2 textboxes and a save button in each row. I need to validate the textboxes when their corresponding save button is clicked. ...

Utilizing JavaScript and JSON to Retrieve Array Elements by Key Names as Indexes

I'm looking for a way to access elements in an array using unique key names instead of numerical indexes. Specifically, I'm developing a Discord bot where each server has its own settings. When a message is sent on a server, I need to retrieve th ...

Exploring the concept of type identification in interpreted dynamic languages

How do dynamic scripting languages like Python, PHP, and JavaScript determine the datatype of a variable? /* C code */ int a = 1; int b = 2; int c = a * b; In the above C example, the compiler recognizes that 'a' and 'b' are integers. ...

Using React.js to create a search filter for users

When using useEffect with fetch(api) to set [search], I encounter an issue where "loading..." appears each time I enter something in the input box. To continue typing, I have to click on the box after every word or number. I am seeking advice on how to pr ...

Guide on modifying values using both input fields and buttons at the same time

I am facing an issue with my input field that is designed to accept numbers. I want the value to be changed both via keyboard input and buttons. The buttons are functioning correctly unless I try to use keyboard input as well. For instance, if I enter 10 ...

Guide on troubleshooting Node TypeScript in Visual Studio Code when the JavaScript source is stored in a separate directory

When using Visual Studio Code, I am able to debug and step through the TypeScript source code of Main.ts. This is possible as long as the JavaScript and map files are located in the same folder as the TypeScript source. This setup works well in this struc ...