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

Demonstrating various elements within an application using Vue3

I created two components and attempted to display them in a Vue 3 application. Here is my HTML code: <div id="app"> <image_preview> URL: [[image]] </image_preview> <file_uploader> Counter:[[coun ...

Error: Router.use() expects a middleware function, but received an object instead

I've made some adjustments to my code following middleware changes in the latest version of express, but I'm running into issues. Can someone please assist me? Here is my index.js file: const express = require("express"); const app = express(); c ...

PDFMAKE: A Guide to Duplicating Elements in the 'Content' Array

I have an Array within Items. My goal is to display them in a Table format using PDFMake. table: { multiple pages headerRows: 2, widths: ['auto', 100, 200, 'auto', 'auto', 'auto'], body: [ ...

Passing a return value to ajax success within an Express application

I am trying to retrieve a value from an included file and use it in the success function of an ajax call within Express. Below is my code for app.js: var userdetail = { "useremail":req.body.useremail, "fname" : req.body.fname, "lname" : req.bo ...

"Explore the convenience of viewing two separate videos on one webpage, each in its own

After extensive research, I have been unable to find any information on the issue at hand. I am attempting to use the jquery plugin OkVideo to display different videos in two separate "section" tags. However, even after explicitly assigning IDs to each con ...

Nested modal in native app utilizes the React Carbon TextInput component for an uneditable input field

As a newcomer to React, I have encountered an issue with the Tauri framework used to bundle my React application as a desktop app. Specifically, I am facing a problem where the TextInput field, nested inside a modal and utilizing React Carbon components, i ...

The function is malfunctioning following the alert

I am experiencing an issue with my renumbering list function. I have a delete button on the list that triggers a confirmation alert, but after the alert is shown, the renumbering function stops working. Here is my script: <script type="text/javascript ...

Troubleshooting: Issue with append function not functioning properly after click event in Angular

I am struggling to implement a basic tooltip in AngularJS. Below is the HTML I have: <span class="afterme" ng-mouseover="showToolTip('this is something', $event)" ng-mouseleave="hideToolTip();"> <i class="glyphicon glyphicon-exclama ...

Retrieve information in JSON format using AngularJS by fetching data from SQL through PHP

My objective is to retrieve data from a mySql database using PHP, convert it to JSON, and then display it through AngularJS. Although I have successfully completed the steps leading up to this point, I am facing issues with the final step. Below are the de ...

Warning: An instance of a class does not have a property called "list_data

When trying to access data using an API to display on an HTML table, the code usually runs smoothly. However, occasionally an error occurs: Notice: Undefined property: stdClass::$list_data Notice: Trying to get property of non-object I have searched for ...

Upon reinstalling the node_modules in my Nuxt.js project, I encountered the error message "Must use import to load ES Module:~"

After reinstalling node_modules, I encountered an issue where ufo and node-fetch were missing. Upon adding them back in, running npm run dev resulted in an error when opening localhost in a browser. This same error persisted when cloning the project onto ...

Exploring the Power of Ajax Integration with Mongodb

I have been trying to figure this out for a while now, but I'm lost. I am attempting to use Ajax to retrieve information from a collection named 'reizen' in MongoDB. My goal is to cycle through all elements within the collection and extract ...

Revamping status and backend systems

Seeking advice on the most effective method to execute a HTTP PUT request within my react application. A Post component is responsible for fetching data from https://jsonplaceholder.typicode.com/posts/1 and displaying it. There's another component na ...

JavaScript popup cannot be shown at this time

I'm encountering an issue with displaying popups using JavaScript. Currently, only the div with class "popup" is being shown. When a user takes action, both popup and popup2 should be displayed but for some reason, it's not working as expected. ...

Adding a MongoDB document at a precise moment of time

Is it feasible to insert data into a database at a specific time? For example: I aim to submit a text to the database in 3 hours => Upon clicking the button on my client side, I wish for the document to be created exactly 3 hours later. Can this funct ...

Constantly showing blank white pages on my website specifically in Internet Explorer 11

I successfully developed a website using react, babel, webpack, and backend Django framework. Everything runs smoothly on Chrome, Safari, and Firefox, but when it comes to IE11, issues arise. Initially, the site functions properly, but after navigating thr ...

Change the way a button interacts with a different element

Currently, I am utilizing SlickSlider from http://kenwheeler.github.io/slick/ and attempting to integrate the Next and Prev buttons with other elements (specifically spans within another container). I have attempted the following: $('button.next&apo ...

Converting Node JS request to an API into React Fetch syntax

I have encountered a problem while developing an app in React-Native that connects with the Hubspot API. Initially, I tried to make the request using the Node JS request module, but it didn't work well with React Native when Expo was involved. Now, I ...

Retrieve the current URL upon page load

I'm currently attempting to parse the URL in document.ready() so I can retrieve the id of the current page and dynamically populate it with content from an AJAX call. However, I've encountered an issue where 'document.URL' seems to refe ...

Unauthorized changes made without verification

I'm in the process of developing a website that allows users to post without needing to create an account. Upon posting, users will be prompted to enter their email address. After posting, users will receive an email with a unique URL that grants th ...