Is there a way to modify the value of a variable within a document by referencing another variable present in the same document?

In my MongoDB collection, each document has three variables:

const moneySchema = mongoose.Schema({
  userID: String,
  tron: Number,
  sccn: Number
})

Using JavaScript, I need to increase the value of sccn by (tron * multiplier) every hour where the multiplier is a pre-defined variable.

I know how to schedule the hourly event, but I'm unsure how to handle the increment operation. This is what I have tried so far:

Money.updateMany(
    { },
    { $inc: { "sccn": { $mul: { "tron": sccnpertrx } } } } }
).catch(err => console.log(err));

Answer №1

This query in the mongo shell will increment the money collection with the following values:

Input documents:

{ _id: 1, coins: 5, gems: 6 },
{ _id: 2, coins: 11, gems: 3 }

Increment query:

var gemsPerCoin = 2;

db.money.find().forEach( doc => { let incVal = doc.coins * gemsPerCoin; db.money.updateOne( {_id: doc._id }, { $inc: { gems: incVal } } ) } );

Updated documents:

{ "_id" : 1, "coins" : 5, "gems" : 16 }
{ "_id" : 2, "coins" : 11, "gems" : 25 }

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

What is the process for embedding JQuery within the <body> tags in Joomla 3.1?

I inserted the following code into my default.php file in Joomla 3.1. <?php JHtml::_('jquery.framework'); JFactory::getDocument()->addScript(JURI::root().'template/mytemplate/js/jquery.min.js'); ?> However, this code only pl ...

A hyperlink unveils a visual and conceals its own presence

I'm a beginner in the world of coding and I have a question about creating a link that reveals a hidden image while hiding itself using HTML. After some research, this is what I've come up with: <a href="javascript: ...

Tips on incorporating the source path from a JSON file into a Vue component

Is there a way to render images if the path is retrieved from a JSON file? Typically, I use require('../assets/img/item-image.png'). However, I'm uncertain how to handle it in this scenario. Component: <div v-for="(item, index) in i ...

Is there a way to change a string that says "False" into a Boolean value representing false?

When retrieving values from the backend, I am receiving them as strings 'True' and 'False'. I have been attempting to convert these values into actual Boolean values, however, my current method always returns true. What is the correct a ...

Issue encountered while exporting a variable in Node.js

Issue with exporting a variable. First File const commander = require('discord.js-commando'); const ytdl = require('ytdl-core'); class exportCommand extends commander.Command { constructor(client) { super(client,{ ...

Error encountered while attempting to download PDF file (blob) using JavaScript

Recently, I have been utilizing a method to download PDF files from the server using Laravel 8 (API Sanctum) and Vue 3. In my Vue component, I have implemented a function that allows for file downloads. const onDownloadDocument = (id) => { ...

Tips for bringing a particular tab into focus when a page initially loads

My webpage features custom links (tabs) that display content when clicked. By default, the first tab is selected and its content is shown, while the rest are set to display:none. Clicking on any other link will assign the 'selected' class to it, ...

Getting the value of a hidden input field within a div by accessing the event.target that initiated the event in JavaScript

I am working with a set of li elements, each containing specific child elements structured like this: <li class="list"> <!--Parent--> <input type="hidden" id="id" value="3"> <!--Child 1--> <div class="cd-1">....</div ...

Creating a Vue application utilizing a function with an unspecified purpose

Looking to create an app with a function that is currently undefined. On the production server, there is a function called __doPostBack which I am calling from my Vue app like this: getLabel(templateName) { __doPostBack(templateName, ""); } Afte ...

Transferring files to Django using AJAX

I am struggling with the process of uploading files to django using ajax. The upload is done within a modal window. The Form <div class="modal fade bs-example-modal-lg" id="fileUploadModal" role="dialog" aria-hidden="true"> <div class="modal ...

Eliminate the need for pressing the "tab" key on my website

I'm currently working on a horizontal web page layout and I'm looking for a way to disable the "tab" button functionality on my page. The issue arises because I have a contact form with textboxes located in the last div, and when users navigate u ...

Setting up popover functionality in TypeScript with Bootstrap 4

Seeking assistance with initializing popovers using TypeScript. I am attempting to initialize each element with the data-toggle="popover" attribute found on the page using querySelectorAll(). Here is an example of what I have tried so far: export class P ...

Unable to convert date data for display on D3 line graph

I am attempting to replicate a line graph similar to the one in the following fiddle link: http://jsfiddle.net/wRDXt/2/ In the example, the date is used as new Date(2013, 17, 1). The JSON data I have is structured as shown below, [{ "_id": "bb68d8a2 ...

Exploring the process of accessing a NextJs API to retrieve data directly from MongoDB

I have developed an e-commerce products API that retrieves data from a MongoDb database. import dbConnect from "../../../lib/mongodb"; import Products from "../../../models/Products"; export default async function handler(req, res) { ...

Ways to include multiple pieces of data in a JQuery Mobile List view

Obtaining JSON data (list of available Hotels within a certain distance) and extracting the following information in JSON format: Name of Hotels, Distance of Hotel from our current location, number of rooms. There might be multiple Hotels within the specif ...

What is MongoDB's approach to utilizing the JSON Schema "oneOf" keyword in the validation process?

I have been experimenting with a JSON schema that includes anyOf, oneOf, and allOf. The schema works perfectly in all scenarios except for oneOf. It is supposed to work only with oneOf, but for some reason, it is not functioning properly. { "bsonType": ...

My attempt to use the Redux method for displaying data in my testing environment has not yielded

I've been attempting to showcase the data in a Redux-friendly manner. When the advanced sports search button is clicked, a drawer opens up that should display historical data when the search attributes are selected. For this purpose, I implemented the ...

Remove all spaces from input fields in angular Typescript, excluding the enter key

I've encountered an issue where the code below removes all spaces, but it's also removing the enter key. Is there a way to remove only spaces and not affect the enter key? static stripDoubleSpaces(str: string): string { if (!!str) { ...

Improving the efficiency of ajax/javascript is necessary as the delay in data retrieval is too significant. There must be a more effective approach to this

Utilizing ajax requests to populate modal popup windows with user-filled data has been my current method. These popup windows, designed as div layouts, are controlled by jquery for showing and hiding. However, there seems to be a noticeable delay in this p ...

What is the best practice for integrating MongoDB into a NodeJS application running on Elastic Beanstalk?

Currently, I am in the process of constructing a web application that requires a database to store user information. The company I am collaborating with intends to deploy the app on Elastic Beanstalk. As someone who is new to cloud technology, I feel compl ...