Adjust the values of a specific field in every document by referencing another field within the same document

Within my database, I store student records that each contain the fields amountOwed and tuition.

The task at hand is to update the value of amountOwed to be the sum of its current value and tuition.

I am considering utilizing a .find query to retrieve all student documents, iterating through each one and updating the database accordingly.

Though, upon reviewing the mongo documentation, I stumbled upon $set(aggregation) and $addFields(aggregation), but unsure if they are suitable for this operation.

Sample student documents:

{"studentName" : "Student1",

 "amountOwed" : 100,

 "tuition" : 100

},

{"studentName" : "Student2",

 "amountOwed" : 0,

 "tuition" : 500

}

The expected output should look like this:

{"studentName" : "Student1",

 "amountOwed" : 200,

 "tuition" : 100

},

{"studentName" : "Student2",

 "amountOwed" : 500,

 "tuition" : 500

}

Is there a way to achieve this with just one database query?

Possibly leveraging updateMany?

Answer №1

If you want to incorporate values, consider utilizing the $add expression in the Mongo Aggregation Query.

Give this query a try:

db.collection.aggregate([
  {
    $project: {
      studentName: 1,
      tuition: 1,
      _id: 0,
      amountOwed: {
        $add: [
          "$amountOwed",
          "$tuition"
        ]
      }
    }
  }
])

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

After installing the latest version of [email protected], I encountered an error stating "Module 'webpack/lib/node/NodeTemplatePlugin' cannot be found."

Upon updating to nextjs version 10.1.3, I encountered an error when running yarn dev. Error - ./public/static/style.scss Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin' Require stack: - /path_to/node_modules/mini-css-extract-plugi ...

Retrieve the corresponding row number in MongoDB using c#

I am retrieving the individual exam result details of a candidate post-examination, which are stored in MongoDB using the C# driver. The collection contains a TotalMarks field that stores the marks obtained in the exam. However, the collection does not in ...

Generate a unique identifier and verify its presence within an array of objects

Is there a way to generate a unique identifier and add it to an object in an array, only if the id does not already exist in any other objects within the array? Within the React code snippet provided below, the "saveColor" function was intended to accompl ...

Utilizing the onFocus event in Material UI for a select input: A comprehensive guide

Having trouble adding an onFocus event with a select input in Material UI? When I try to add it, an error occurs. The select input field does not focus properly when using the onFocus event, although it works fine with other types of input. Check out this ...

Error: Unable to locate module - The specified file cannot be resolved when utilizing an external JavaScript library

I am currently integrating a WYSIWYG editor (TUI Editor) into my Angular2+ application. Since there is no official Angular wrapper available, I have decided to create my own based on an existing wrapper. Due to some installation issues with npm, I saved t ...

Once the Angular project has been initialized, the Button disable attribute cannot be modified

In my Ionic-Angular project, I am creating registration pages where users input their information in multiple steps. For each step, there is a button that remains disabled until the correct information is entered. An issue arises when transitioning to the ...

utilizing vue model attributes with `${}`

I am encountering an issue with my code. Initially, :src="labels[index]" was working fine for me. However, as my codebase expanded, I needed to use ${app.labels[index]}. Simply using ${app.labels} works, but the addition of [index] causes it to b ...

Manipulate JSON insertions and character replacements using JavaScript or Python

I have a JSON file that contains an array of 500 objects. The structure of each object is as follows: { "books":[ { "title":"Title 1", "year":"2012", "authors":"Jack ; George", }, { "title":"Title 2", "year":" ...

What is the best way to link a JavaScript file from a node package in an HTML document?

After developing a Node.js Express App using JetBrains WebStorm, I utilized npm (via File->Settings->Node.js and NPM) to install a package called validator, specifically designed for string validation. The installation of the package went smoothly u ...

Is the .html page cached and accessible offline if not included in the service-worker.js file?

During the development of my PWA, I encountered an unexpected behavior with caching. I included a test .html page for testing purposes that was not supposed to be cached in the sw.js folder. Additionally, I added some external links for testing. However, w ...

Navigating from the online realm to leisure activities

As a web developer with knowledge in PHP, Python, Ruby, and JavaScript, I've tackled various web projects but now I have a strong desire to dive into game development. It may seem like a big leap, but I'm determined to learn and explore this new ...

Argument not accepted in JavaScript

Currently, I am encountering a unique error message while working with a complex function that iterates through elements in my JavaScript onSuccess event. The error I am seeing is: exception encountered : {"message": "Invalid argument.", "description": " ...

A JQuery function linked to the click event of the body element triggers another click event right away

$().ready(function(){ $("#move-to").click(function(){ $("body").bind("click",function(){ alert("foo"); }); }); }); Why do I receive an alert message of "foo" immediately after clicking on "move-to"? When I bind the " ...

Generate a Table Using JSON Data with AngularJS and ng-repeat

I have some JSON data that looks like this: { "Workout1": { "Name": "First", "Rounds": [ { "Exercises": [ { "Name": "Exercise1", "Repeat": 10 }, { "Name": "Exercise2 ...

Update and replace the matching class in a JavaScript variable before appending it to dynamically generated content

I am attempting to substitute a matching class from a JavaScript variable before dynamically appending generated content. The goal is to identify one ID out of all the IDs in this variable and replace the 'hideeee' class with it. While I know thi ...

Executing Selenium WebDriver to interact with a hidden element

Hello, I am interested in learning how to interact with hidden elements and disable them using Selenium WebDriver. I've managed to achieve this with Selenium 1 by using the following code: selenium.click(id="idOfHiddenField"); Unfortunately, this a ...

Switching minimum and maximum input values based on a specific condition: A step-by-step guide

I am looking for a way to reverse the minimum and maximum values of two input elements that I have defined. Is there a way to achieve this using HTML or JavaScript (Angular)? Here is an example of what I am trying to do: <label> Width: < ...

Is it possible for me to avoid html tags inside a class without using the xmp tag?

There are a few ways to approach this question. It's important to decide which method will be most beneficial for your specific needs... Is it possible for JavaScript to recreate the deprecated <xmp> tag using an "xmp" class? Can we replicate ...

Navigating ExpressJS with Two MongoDB Collections Querying

I have successfully implemented a collection model that displays documents based on two properties in the URL path. When the URL contains /red/monday, for example, all images with those specific values are displayed. Now, I want to create a second collecti ...

Every time I initiate the command `mongod --config "C:Program filesMongoDBServer3.0inmongodb.config"`, it seems to loop indefinitely

mongod --config "C:\Program files\MongoDB\Server\3.0\bin\mongodb.config" I am perplexed and agitated by this unexpected behavior. Typically, error messages provide guidance on how to resolve issues, but in this case, the typed ...