Steps to finish (refresh) a mongoDB record

Currently, I am dealing with the following scenario:

An API request from one service is creating multiple MongoDB documents in a single collection. For example:

[
{_id: 1, test1: 2, test: 3},
{_id: 2, test1: 3, test: 4}
]

Subsequently, a second service reads these documents and retrieves additional information. As a result, I am constructing an object like:

[
{_id: 1,  newValue: 4},
{_id: 2,  newValue: 4}
]

Now comes my question: Is it possible to update all the documents at once using the "_id" value? The challenge is that I want to avoid updating each document individually due to their large number. Therefore, I am considering deleting all the existing documents and inserting them again with all the necessary information. What are your thoughts on this approach?

Answer №1

To avoid the negative consequences of mass deletion followed by re-insertion, it is recommended to perform multiple updates in bulk using the bulkWrite method:

var bulkOperations = [];

for each item requiring processing {
        prepare _id and newValue ... ;
        bulkOperations.push({
          "updateOne": {
                    "filter": { "_id": targetId },
                    update: { $set: {"newValue": desiredValue } }
                }
            });
    });

// Execute a single batch of updates. This process could be enclosed within a transaction as well:
printjson( db.foo.bulkWrite(bulkOperations) );

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

Utilizing ES6 Imports and Managing npm Packages

Can anyone provide a guide detailing how ES6 import should function with npm packages, as opposed to JavaScript module files? Additionally, is there documentation available regarding the use and significance of "module" as a top-level key in an npm packag ...

Guide on using JavaScript to automatically scroll a HTML page to the top on any mobile browser

Can JavaScript be utilized to smoothly scroll an HTML page to the top? I am looking to achieve this with a stylish animation that functions correctly on all mobile browsers. jQuery is the library I am using on this particular page. Thank you, ...

What is the process for installing gulp-cli version 4.0?

Need help with the gulp-cli installation. npm install -g "gulpjs/gulp-cli#4.0" Experiencing an error message: npm ERR! code 1 npm ERR! Command failed: C:\Program Files\Git\mingw64\bin\git.EXE checkout 4.0 npm ERR! error: pathspe ...

The error message "TypeError: winston.createLogger is not a constructor" indicates that there is a

Why is winston.createLogger(); not recognized as a constructor? Despite some users attempting to revert back to [email protected], I have not been successful with that method. I am currently using the most recent version of winston. Below is my logge ...

"Vue.js integrates seamlessly with Tracking.js for advanced tracking

Has anyone successfully integrated the tracking.js library into a vueJS application? I followed these steps to install the package: npm install --save tracking After that, I defined the library in my main.js file like this: import tracking from 't ...

Developing a versatile Angular2 component that has the potential to be utilized across various sections of a website

Use Case: I need to display a processing screen during asynchronous calls to keep end users informed about ongoing activities across multiple sections of the website. To achieve this, I decided to create a reusable component at the global level. Issue: As ...

Comparing getElementById with $('#element') for retrieving the length of an input field

Consider the following scenario: <input type="text" id="apple"> Why does the first code snippet work? $(document).ready(function () { alert($('#apple').val().length); }); However, why does the second code snippet not work as expecte ...

Unable to completely conceal the borders of Material UI Cards

Despite my efforts to blend the card with the background, I am still struggling with the tiny exposed corners. I've spent hours searching for a solution, but nothing seems to work. I've tried various methods such as adjusting the border radius in ...

How come I am getting the desired section from my split string only after running the function twice?

I've been working on a function that retrieves data from a form and sends it to a POST request, which in turn sends it to my MongoDB database. The following code snippet showcases the process of uploading an image to IPFS, extracting the IPFS hash fro ...

Is there a way to prevent tags from wrapping and showcase them all in a single line when utilizing the jQuery select2 plugin?

I have a requirement to prevent tags from wrapping and instead display them in a single line using the jQuery TagIt plugin. Check out my preview: https://i.stack.imgur.com/lYhsi.png My goal is to have all the tags displayed on a single line without wra ...

Having trouble accessing the root route in production environment

After creating a basic Node application with 5 routes that serve different HTML documents, I encountered an issue. While all the routes function properly when running on localhost, in production my root route displays a 404 error page, indicating that the ...

Is the × symbol added from JavaScript not able to be clicked on?

In my javascript code, I have added HTML content dynamically using the following method: var response = { message: "sample messsage" }; $('#main-content').append( '<div class="alert alert-danger alert-dismissable">'+ & ...

Parent controller was not in command before Child执行

When working with a parent view and a child view, I encounter an issue with accessing a json file. In the parent view, I retrieve the json file using the following code: $scope.services = Services.query(); factory('Services', function($reso ...

Arrange the child elements of a div to be displayed on top of one another in an HTML document

I am struggling with a div containing code .popupClass { width: 632px; height: 210px; position: absolute; bottom:0; margin-bottom: 60px; } <div class="popupClass"> <div style="margin-left: 90px; width: 184px; hei ...

Using the JQuery template with $.get function does not produce the desired result

Working on populating a table using a Jquery Template can be tricky. One challenge is incorporating a json file via an ajax call for the population process. $(document).ready(function() { var clientData; $.get("/webpro/webcad/lngetusuario", funct ...

Error: Your Discord bot is unable to send a message as it is empty. Please check Discord

I have been developing a Discord Bot to verify Roblox accounts. Although my script is prepared and the command "-verify" can be executed, an error arises: (node:22872) DeprecationWarning: The message event is deprecated. Use messageCreate instead (Use `n ...

Error: Vue.js is unable to find the reference for "_vm.KisanData" and throws a TypeError

I need assistance in fixing an error that I am encountering. The issue arises in this method where I am using KisanData, but I am unable to resolve it. const API_URL = "http://localhost:3000/User"; export default { name: "home", info(){ ...

Creating credentials for the npm registry URL

Recently, I encountered an issue while trying to use npm to install a package from a specific URL: . To address this problem, I took the following steps: Set strict-ssl to false using the command npm config set strict-ssl false. Modified the registry by ...

Angular downgrades from version 13.3.8 to 13.3.7

When I input the command: ng v I am shown the version as "Angular: 13.3.8" in the image. Can someone explain where this version is coming from and how can I change it back to 13.3.7? Furthermore, I noticed that the packages listed in the screenshot are d ...

Is there a way to implement field validation in a Vue wizard form?

Trying to implement form validation using Joi in a Vue wizard form, but not sure how to set it up correctly. The objective is to control the fields before progressing to the next and final page using the next() method. I want to keep the simplicity of th ...