Ways to send distinct values to updateMany $set in mongodb

I have encountered an issue while trying to generate unique passwords for each document in a MongoDB collection. The current function I am using, however, generates the same password for every user.

Below is the code snippet that I am working with:

  function createPasswords(){
     db.collection('users').updateMany({}, {$set:{password: GeneratePassword(12, false)}});
    
    }

My expectation was for the GeneratePassword function to run for individual documents, but it appears to only execute once, resulting in identical random passwords for all users in the collection.

Therefore, my question is how can I modify this setup to generate distinct passwords for each user simultaneously using updateMany.

It's worth mentioning that the GeneratePassword function is not a custom implementation, but rather utilizes the password-generator package.

Thank you in advance!

UPDATE

I attempted the following code based on turivishal's response provided below.

 db.collection('users').updateMany({},[{
    $set: { updated: 'true',
      password: {
        $function: {
          body: function() {
            $function: {
              function passGen(param1, param2) {
                return GeneratePassword(param1,param2)
              }
            return passGen(12, false); 
            }
          },
          args: [],
          lang: "js"
        }
      }
    }
  }]);

When executing this code, it resulted in the following error:

MongoServerError: Invalid $set :: caused by :: The body function must be specified.

If anyone could point out what might be going wrong here, any guidance would be greatly appreciated.

Answer №1

When it comes to updating documents in MongoDB, the update() / updateMany() method is a powerful tool. This method allows for a single write operation that can modify multiple documents simultaneously while ensuring atomicity at the document level (although not for the entire operation, according to the docs). However, it does not support updating different values in each document of a collection.

If you need to update documents individually or want more flexibility in your update statements, consider using an update with aggregation pipeline query starting from MongoDB 4.2. This feature allows for more expressive updates and introduces the $function operator in MongoDB 4.4, which enables custom aggregation functions or expressions in JavaScript.

Keep in mind that this approach may impact query speed and performance, so it's best suited for one-time processes. Additionally, note that this query requires support from MongoDB 4.4 or higher versions.

db.collection('users').updateMany(
  {},
  [{
    $set: {
      password: {
        $function: {
          body: function() { 
            
            // Define your custom password generation method here
            function GeneratePassword(param1, param2) {
              // ...
            }

            // Call the internal method to generate a password
            return GeneratePassword(12, false); 

          },
          args: [],
          lang: "js"
        }
      }
    }
  }]
)

Try out this query on the Mongoplayground

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 Mongoose's Find() method will retrieve the document that includes the specified value within an object

I am utilizing MongoDB and Express. Within my collection, I have all the countries which include states and cities. View a snapshot of part of the collection When using Find(), it returns all documents with all states and cities in the country instead of ...

What is causing the button within my ExtJS grid to display as "[object Object]"?

Within an ExtJS grid, I am facing a scenario where I need to display a button in a specific column when the content of a cell meets certain criteria. To achieve this, I define the column with the button using a rendering function as shown below: { he ...

Generating progress bar in Javascript while exporting CSV fileCan JavaScript export CSV and

Looking for a way to add a progress bar while generating and serving a CSV file via ajax? The database-heavy process is causing a delay, so I need a loader on the screen that disappears once the task is complete. It should be done with ajax or stay on th ...

Reloading data in Angular using jQuery DataTables

After successfully implementing the jQuery datatables library, I encountered an issue where new data retrieved from my API was not displaying inside the datatable as expected. Instead, it was being shown below the table using ng-repeat. It seems that the d ...

Dark opaque background image with Material-UI styling

I'm enclosing all the widgets within a CardMedia component, and adding an image. return ( <CardMedia image={bg} className={classes.bg}> <main className={classes.content}> <div className={classes.toolbar} /> <Grid contai ...

Alter the DOM element every ten seconds

Is there a way to modify a DOM element every 10 seconds? I attempted the following approach: var endurance = angular.element('.progressbar').height(); var endurance2 = angular.element('.progressbar').css('height', endurance- ...

`Can incompatible Typescript types be allowed for assignment?`

Currently, I am faced with the challenge of sharing type definitions between my server and front-end. These definitions are stored in a separate npm package that both installations utilize. The issue arises on the front-end where variables containing Objec ...

Utilize key-value pairs to reference variables when importing as a namespace

Is it feasible to utilize a string for performing a lookup on an imported namespace, or am I approaching this the wrong way? Consider a file named my_file.ts with contents similar to: export const MyThing: CustomType = { propertyOne: "name", ...

Activate the class using Vue with the v-for directive

I'm curious about the v-for functionality. Why is it necessary to use this.activeClass = {...this.activeClass} to update the component? I noticed that the component does not update after this line of code. if (this.activeClass[index]) { ...

Is there a way to dynamically set the active panel of a JQuery Accordion when making a call?

Currently, I am faced with a scenario where I need to implement a greybox popup window using jQuery Accordion from the main page via links. I am curious to know if it is doable to specify a default active panel for the accordion when calling it. Below is ...

Troubleshooting: Resolving the "npm ERR! missing script: start" Issue

I'm encountering the error below: npm ERR! missing script: start npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\..\AppData\Roaming\npm-cache\_logs\2019-04-27T18_02_39_6 60Z-debug.log Th ...

Utilizing SlickGrid and DataView for calculating totals efficiently without the need for grouping

I am attempting to utilize Slick Grid and DataView to calculate column totals similar to the example shown here: . However, I do not want to group my rows. Therefore, I attempted not passing a getter and formatter into the dataView.setGrouping(..) method. ...

Creating impenetrable div elements with JavaScript or jQuery

I'm currently working on creating solid blocks using DIVs positioned side by side both horizontally and vertically. I've successfully achieved this when the divs have equal heights. However, an issue arises when a div has larger dimensions; it en ...

Cautionary alert while displaying a data binding from a controller in AngularJS

Adding a numerical value to the controller: this.myValue = Number(elem.toFixed(2)); Then placing it inside an input form: <input class="my-input" type="number" value={{$ctrl.myValue}} ... > Although the value ...

Access the most recent state value with React's Context API

Trying out the React context API, Take a look at the someComponent function where I pass the click event (updateName function) to update the value of state.name from the GlobalProvider function. After updating state.name, it reflects in the browser but t ...

How to retrieve the data variable in Vue JS script

I recently started using vue.js and I'm working with version 2.5.13. In my component file script, I am trying to access a data variable but it keeps returning as undefined. The id attribute in the component is displaying the correct value, however w ...

Combining and mapping arrays in Javascript to form a single object

I am using the following firebase function this.sensorService.getTest() .snapshotChanges() .pipe( map(actions => actions.map(a => ({ [a.payload.key]: a.payload.val() }))) ).subscribe(sensors => { ...

Comparing global variables in ng-switch: Best practices

I'm currently utilizing the AngularJS $rootScope object to expose some global constants that should be accessible to both controllers and views: var app = angular.module('myApp', []); app.run(function ($rootScope) { $rootScope.myConsta ...

Generate a dot density map with the help of Google Maps

I am looking to create a dot density map using Google Maps for my state. I have all the counties outlined with their respective populations, and I want to scatter dots randomly within each county to represent the population. The goal is to make a dot densi ...

Is there a way to restore the face's original orientation after it has been rotated

Just to note, I am aware that this question has been asked before. However, the previous answers did not address my specific situation and requirements. Currently, I am developing a Rubik's cube using three.js. To achieve lifelike rotations, I am rot ...