Updating array of documents in MongoDB with a new array of documents

Is there a way to properly update an array of objects in a collection without having to remove and re-insert them? I am worried about losing data if the insert operation fails after removing the existing array. How can I efficiently update all documents in a collection?

Inserting an array of documents:

collection.insert(arrToInsert, function(err, results){
    console.log(results.ops);
});

Current method of updating inserted array (not ideal):

collection.remove({}, function(err){
    collection.insert(arrUpdated, function(err, result) {
        console.log(results.ops);
    });
});

I have attempted using collection.update but it does not support updating arrays.

Edit: For example: Insert this initial array:

[
    {_id:0,name:"Harry"},
    {_id:1,name:"Jacob"},
    {_id:2,name:"Bob"}
]

and then transform it into:

[
    {_id:0,name:"Dennis"},
    {_id:1,name:"Peter"},
    {_id:2,name:"Ghandi"}
]

My actual scenario is more complex as the array includes additional key/value pairs and requires multiple types of updates.

Answer №1

Are you familiar with .bulkWrite()? This method enables multiple update operations ( Insert/Update/Remove) to be performed on the same collection in a single batch request, making it a powerful tool for efficient data manipulation. In essence, when using either .insert() or .insertMany() with an array of documents, what is actually being invoked behind the scenes is .bulkWrite().

If you were to carry out a new update, your code snippet would look something like this:

var arrToUpdate = [
    {_id:0,name:"Dennis"},
    {_id:1,name:"Peter"},
    {_id:2,name:"Ghandi"}
];

collection.bulkWrite(
  arrToUpdate.map( d => ({
    "replaceOne": {
      "filter": { "_id": d._id },
      "replacement": d
    }
  })),
  function(err,result) {
    console.log(result)
  }
)

In this context, replaceOne serves as a substitute for an "update" operation without requiring any modifiers like $set.

The key advantage here is that similar to using .insert() with an array or .insertMany(), only one request and response are sent to the database despite there being multiple operations within that single request.

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

How can I display an iframe element only if it exists within an object in Angular?

I'm currently exploring options to specifically display the iframe element within a block of HTML content being sent to my Angular application. While I can use a *ngIf directive in my template to check for the presence of the tag, I am unsure of how ...

Organize array by "categories" in Javascript and preserve the original sequence

There is a dataset presented below: [ { "name": "Item1", "section": "section1", "total": 3, }, { "name": "Item1", "section": "section2", "total": 4, }{ "name": "Item1", "section": "section3", "total": 7, }, { "name" ...

Exploring the possibilities of incorporating Bootstrap 4 or ng-bootstrap elements into Angular 4 development

We are considering the use of Bootstrap 4 within an Angular 4 application by either importing their styles and JavaScript directly, or utilizing ng-bootstrap Angular components for improved performance and compatibility with the Angular app. We would lov ...

Rendering v-html in VueJS requires a delayed binding value that can only be triggered by clicking inside and outside of a textarea control

I'm currently experiencing an issue with a textarea that is bound to a v-model with a specific value. The problem arises when the content of the textarea is changed via JavaScript - the displayed value, represented by {{{value}}}, doesn't update ...

What are the steps for running app.js deployed on a remote server using the local bash terminal?

After launching my web application on GoDaddy, which is built in Node.js, I have encountered a dilemma. In order to run app.js, I currently rely on my computer's bash command prompt. However, this poses an issue - if I were to shut down my laptop, the ...

The issue with Mongoose's nested populate feature not functioning properly with Q

As I delve into promises, I am experimenting with optimizing my nested populates by utilizing Q library. The issue at hand is that the layers are not executing in the intended order, leading to data not being passed through to subsequent layers effectivel ...

Mongodb is incompatible with MacOS operating systems and will not operate on this

For years, I've been smoothly operating MongoDB on my Mac (currently Sonoma 14.6.1) by installing it via brew with the command: $ brew install mongodb-community Then starting it using: $ brew services start mongodb/brew/mongodb-community I' ...

The eternal dilemma: async with axios or simply axios, which will you choose?

Is there a difference between these two useEffect functions? useEffect(()=>{ async function fetchData(){ await axios .get(path, config) .then(resp=>console.log(resp)) .catch(error=>console.log(error)) } fetchData(); },[ ...

HTML content for Bootstrap 5 popover

I've been utilizing Bootstrap 5 popover, but it doesn't seem to display the HTML content I need. I came across a solution on this particular thread: How can I include an html tag attribute in bootstrap 5 popover setAttribute()? It worked well ...

Certain cases will see success with iPhone jquery/ajax functionality, while others may encounter

I am facing an issue with multiple pages in my project that utilize AJAX to submit a form to django. While the buttons work perfectly on various platforms and browsers like Chrome, Firefox, and desktop Safari, they seem to malfunction specifically on mobil ...

Strings that automatically adjust to fit the content from a JSON object

I have a JSON object with a long string that I want to display. The string looks like this: "String":"<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever si ...

In JavaScript, what do we call the paradigm where a variable equals a variable equals a function? Let's take

Feeling a bit overloaded at the moment, so forgive me if this question seems too simple. I managed to accidentally write some code in Jest for testing a Vue application that actually works: const updateMethod = wrapper.vm.updateMethod = jest.fn() expect(u ...

Eliminate all the key/value pairs in an array of objects using underscores

Is there a more efficient way to remove all key/value pairs from an array of objects? For example, consider the following array: var arr = [ { q: "Lorem ipsum dolor sit.", c: false }, { q: "Provident perferendis veniam similique!", c: fal ...

The URL provided by window.location is not accurate

I'm facing an issue with the code window.history.pushState("", "title", myCtxURLVersion); which is supposed to change the current URL of the page. However, when I implement this code, the URL displayed is incorrect. For example, even though the brows ...

Using javascript to close a popup window

On one of my webpages, there is a button that, when clicked, triggers a popup window to appear. Within this popup window, there is a 'Close' button that, when clicked, should close the popup window while leaving the main page unchanged. What is ...

JavaScript is failing to update the table values as users interact with it

I've created an HTML table and used PHP to populate the values. The goal is to allow users to update order statuses with a status and message input. Initially it works fine, but after multiple uses, it either updates the wrong row or doesn't up ...

Previous declarations aren't being carried out during a synchronous ajax request

One of the functions I'm working with looks like this: function m1(){ $('.loader').show(); var xargs={ type : 'POST', url : resourceUrls["listUrl"], data : "sId="+sId, async:false, ...

Adjust the transparency of a navigation bar independently from the transparency of the text within the navigation bar

Seeking assistance on adjusting the opacity of this navbar without affecting the text within it. Any tips on changing the text color as well? <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#" ...

Transform a JavaScript array using key value pairs sourced from a JSON document

I am currently working on developing a feature to detect and flag inappropriate comments within my application. One approach I am taking involves splitting the comment into an array of strings. I am now looking to implement a JavaScript function that can ...

Enhancing the functionality of XMLHttpRequest.open()

How can I intercept and modify the arguments of the XMLHttpRequest.open() method? I attempted using the proxy method, but it was unsuccessful. I removed the override when XMLHttpRequest() was called: (function() { var intercepted = window.XMLHttpReque ...