What is the most efficient method for completely updating every field in a MongoDB document?

If I need to update an entire document and overwrite all fields except for _id, which of the three methods is the most efficient in terms of resource consumption:

1. Setting the complete document as the update parameter, passing all fields

Example:

collection.update({_id: docId}, {$set:updateDoc});

2. Calculating a delta document between the original and updated version

Example:

const originalDoc = collection.findOne(docId);
const deltaDoc = calculateDeltaFct(originalDoc, updateDoc); //get changed fields
collection.update({_id: docId}, {$set:deltaDoc});

3. Utilizing the Mongo 3.2. replaceOne function

Example:

collection.replaceOne({_id: docId}, {$set:updateDoc});

I have some assumptions about the advantages and disadvantages of each method, but I want to make an informed decision on what to choose and why. It's difficult to measure precisely, so any help would be appreciated.

Background:

I have a metrics collection where many documents are frequently updated with varying fields, making it challenging to write specific update methods for each field. Instead, I plan to update all fields by inputting all data, simplifying my code with just one universal update method.

Update:

In my setup, there are no embedded subdocuments in the structure. Additionally, I do not have sharding or replication in my (dev) environment.

Furthermore, I have discovered a method (collection.explain) that I will use to conduct further research on this topic. Any assistance or guidance is greatly appreciated.

Answer №1

When deciding between updating old information or overwriting it completely, the choice between using update or replaceOne in your code boils down to a few key factors. Consider the size of your dataset and whether time efficiency is a priority for you. Personally, based on my experience working with similar collections, I would recommend leaning towards using replaceOne.

From what you've described, it seems like the second option you mentioned might not be the most memory efficient or effective solution. If you're simply updating existing data without worrying about losing previous information, there may be no need for such complex calculations.

Answer №2

One method to update the entire document, excluding the "_id" field, is to delete unwanted fields from the object before updating.

Note: Make sure your "updateDoc" includes the _id field.


The goal was to update all fields without explicitly listing them.

Initial attempt to update all fields:

await examCollection.findOneAndUpdate(
  {_id: new ObjectID(this.examId)},
  {$set: this.data}
)

However, the this.data object contained the _id field that I did not want to update. To work around this, I removed the unwanted fields from the object.

Successful update of document fields, except specified ones:

// (1) Remove fields that should not be updated
delete this.data._id 

// (2) Update MongoDB document
await examCollection.findOneAndUpdate(
  {_id: new ObjectID(this.examId)},
  {$set: this.data}
)

This approach made it easier than specifying all fields I wanted to update, especially since the fields could change in the future.

I hope this strategy proves helpful!

Note: I handled field specification earlier in a separate file rather than immediately before updating as shown in the example, with the same result.

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

Separating the rules for development and production modes in the webpack configuration file

I'm currently in the process of working on a front-end project using HTML. Within my project, I have integrated the Webpack module bundler and am utilizing the image-webpack-loader package for image optimization. However, I've encountered an issu ...

Quick method to populate an array with elements

I need to populate an array with a large number of objects. Currently, my approach looks like this: let useVertices = []; const len = this.indices.length; for(let i = 0; i < len; i++){ let index = this.indices[i]*3; useVertices.push(new THREE.Ve ...

Error retrieving api data following update to date format

After making some adjustments to the date format required by a railway API, I am facing an issue where no train data is fetched upon clicking the submit button. Below is the code snippet: searchTrain(e) { e.preventDefault(); let journeyDate = ...

Dealing with TypeScript and the Mongoose loadClass problem

Working with Mongoose's class schemas has been very beneficial for me. Incorporating TypeScript into my Node project has enhanced the development process. I made sure to refer to Mongoose the Typescript way...? in order to ensure that my Model align ...

"Locate and modify data in mongoDB, or add it if

I am currently utilizing mongoDB along with Mongoose. Here is the schema I am working with: { "group" : "items" : [ { "name": "aaa", "value": "aaa_value", "description": "s ...

Vue: updating data on the server by sending it through an axios.put request

Managing user account information is a key feature of my application. Users have the ability to edit their details by simply clicking on the edit button, which triggers two different containers to display depending on whether the edit mode is activated or ...

The event listener for 'ended' is triggering multiple times

I am in the process of developing a music app, and my goal is to have the next song automatically play when the current one ends. However, I am facing an issue where the EventListener seems to be triggered multiple times in succession - first once, then tw ...

What strategies can I implement to prevent position: absolute from obscuring my content?

I am currently experiencing an issue with my Google Map loading within a tab. The container div has the position set to absolute. Although the map displays correctly, I am encountering a problem where it covers any content I try to place underneath it. My ...

Arranging null values and numbers to imitate the behavior of the tabindex HTML attribute

Currently, I am facing a rather unusual issue with JavaScript sorting. As I delved into the complex world of sorting, I found myself in need of some guidance: My goal is to replicate the functionality of the tabindex HTML attribute, which alters the order ...

Structuring files with AJAX, PHP, Javascript, and HTML

Explaining my dilemma in detail might be a bit abstract, but I'll try to do my best. In one of my PHP files, I have HTML code that includes text boxes and a submit button. This file serves as the main page and is named mainHTML.php The text boxes ar ...

Display the dropdown selected value within a Laravel Blade template

I am facing an issue with passing the selected value from a drop-down to another Blade file in Laravel. I have tried using Ajax and jQuery, but it doesn't seem to work for me. I want to display the selected value on the content.blade.php page without ...

Jquery Mobile: Navigating back to the first page after calling changePage

In the process of developing a mobile app with phonegap/cordova and jquery mobile, I encountered an issue where the user is supposed to land on a specific page from a status bar notification. However, the app initially displays the default page briefly bef ...

Ways to access an array's value using a variable in jade

Having trouble understanding why a variable cannot be used to call a value in an array using JS/Jade. This issue arises within a script on a .jade file. The array contains around 400 entries, and one of them is shown below: myFood[10]['Cake'] = ...

Tips for ensuring the vertical scroll bar is always visible on a div element

I need help with maintaining a vertical scroll bar on a div regardless of its height. .myclass { overflow-y: scroll; } <div class="myclass"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the in ...

Evaluation of Library (VueJS) - Displaying various components in an individual test case

Just starting out with testing and have a simple question: I am working on testing a checkbox component. I understand the basics, but how can I render multiple components within one it block? Here is my current code. I am stuck on the second test where I ...

transmit data via Javascript to interact with a Python web application

I'm having issues sending a json object from JavaScript to a Python webservice. The service keeps treating it as a string. Here are the codes for both client and server sides: CLIENT SIDE: $("#button").click(function () { $.ajax({ ...

invoke scrollToPosition function in React Native

I am trying to execute a function once the scrolling momentum is finished in my react native SectionList. After going through the documentation, I discovered onMomentumScrollEnd. However, the problem is that onMomentumScrollEnd only works when we manually ...

JavaScript - Reveal a div when a grid item is clicked

I have created a grid with a 5x7 layout using divs. I am trying to achieve a feature similar to the Netflix interface where, upon clicking on a div, a larger div will appear beneath it. This larger div should expand to 100% width of the parent container, p ...

Encountering an error stating that 'coordinates should consist of an array with two or more positions'

Utilizing turf.js to generate a line depicting the path of an individual while their location is tracked. An array of coordinate arrays resembling Turf.js (lineString) is causing this error: Uncaught Error: coordinates must be an array of two or more posi ...

What is the best way to obtain the value of a radio button using ajax?

Here is the search button in my PHP file. I am unsure of how to connect the radio button to the JavaScript file. <button id="submit">Search</button> This is the starting point in the JavaScript file var xhr = new XMLHttpRequest(); f ...