Increasing several array elements within a MongoDB object

I have been struggling with this problem for some time now. My goal is to update multiple array values in the same object with a single query.

The data in the database appears as follows:

  id: 616f5aca5f60da8bb5870e36
  title: "title"
  recommendations: {
    616f65705f60da8bb5870e37: [
      0: 25,
      1: "title 2"
    ],
    61e83b48e498cc5aae9dc741: [
      0: 22,
      1: "title 3"
    ]
  }

So far, I've attempted both preparing a statement like this:

const fetchQuery = "recommendations.616f65705f60da8bb5870e37.0 : 1, recommendations.61e83b48e498cc5aae9dc741.0 : 1";

const result = await videoGamesCollection.updateOne(
        { _id: ObjectId(req.body.parentId) },
        { $inc: fetchQuery }
      );

And also tried using array filters:

const result = await videoGamesCollection.updateOne(
        { _id: ObjectId(req.body.parentId) },
        { $inc: {"recommendations.$[elem].0": 1} },
        {arrayFilters: [{"elem":{$in:[req.body.voteIds]}}]}
      );

Unfortunately, neither of these methods seem to be working. I am wondering if it is possible to achieve this or if my only option is to convert to an array of arrays instead?

Thank you!

Answer №1

Make sure to put

recommendations.616f65705f60da8bb587ba82.0
within quotation marks, such as:

let total = await videoGamesList.updateOne(
        { _id: ObjectId(req.body.parentId) },
        {
          $inc: {
             "recommendations.616f65705f60da8bb587ba82.0": 1,
             "recommendations.61e83b48e498cc5aae9dc741.0": 1 
        }
      );

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

The issue with MVC4 and Ajax requests for converting image ByteArrays appears to be problematic

I am attempting to change an image in my View with a click event. However, when the controller returns a byte array, the original image is replaced with an empty one. Below is the code from my Controller: [HttpPost] public byte[] GetSelectedI ...

Issue with jQuery Master-Detail dropdown list selection

Having trouble isolating the code in this jsfiddle script. Despite my efforts, it seems that isolation is not working as expected and Firebug isn't showing any errors on the console: <!DOCTYPE html> <html lang="en"> <head> ...

What is the correct way to utilize the karma-ng-html2js-preprocessor?

I'm working on a directive called stat24hour: angular .module('app') .directive('stat24hour', stat24hour); function stat24hour(req) { var directive = { link: link, template: 'scripts/widgets/templ ...

When triggered, the onClick event will launch multiple Material-UI dialogs simultaneously

I'm working on creating a user-friendly employee directory using Material-UI's dialog modals. However, I'm facing an issue where clicking on any employee card opens all dialog boxes instead of just the one related to that specific employee. ...

When I restart my NodeJS/Koa.app with Mongoose, I noticed that the Mongo data gets erased

I'm facing an issue where the data stored in my MongoDB instance gets deleted whenever I restart my Node/Koa.app. This application utilizes Mongoose to connect to the local Mongo instance. Here's the code for reference: app.js (I have written c ...

Organize information received from a post request into a JSON template

I am attempting to automatically sort information from a post request. Each category is identified by a number (0 -> 1 -> ....) There is one title defined for each category with its respective number, for example: "0": "Are planes fly ...

In the production build of Next.js server components, fetching is not executed, unlike in development where it is carried out

SOLVED At the beginning of my project, I was considering using internationalization for translating the pages. In the next.config.js file, there are some configurations for internationalization like the one below that caused issues: //next.config.js const ...

Tips on customizing the appearance of JavaScript output?

I recently created a plugin for my website with JavaScript, and one of the lines of code I used was output.innerHTML = "Test"; Is it possible to apply CSS styles to this element, or is there an alternative method? ...

Establishing the focal point and emphasis within a textarea input field

I am presenting a textarea input through PHP with the following command : print " '<textarea rows='16' cols='30'>$flist'</textarea><BR>"; I want the textarea to receive focus and automatically select the co ...

How can I fill an HTML table with data stored in a JavaScript array of arrays?

I am struggling to populate an HTML table with data formatted as an array of arrays. Despite my efforts in writing the code, the data is only showing up in a single row. I have tried mapping the data in a nested loop but I am unable to implement it correct ...

Direct back to the current page post deleting entry from mongodb

After removing data from MongoDB, how can I redirect to the same view (handlebar)? I tried using res.render, but it shows that the website cannot be reached. Thank you for your assistance. Controller Logic var express = require('express'); va ...

How come the JavaScript map() function displays my feature when the forEach() function didn't work? This issue arises while working with React and Next

There was an issue with rendering my feature because React did not recognize that the state was changing. By switching from using forEach() to map(), I was able to successfully render the feature as intended. This feature retrieves user subscriptions from ...

HtmlUnitDriver fails to execute javascript while loading a page from a URL

My issue revolves around testing my website page, where elements displayed with javascript are missing when viewed through the HtmlUnitDriver. I am currently using selenium-java version 3.141.59 and htmlunit-driver version 2.33.3. Below is a snippet of my ...

How to verify if an object is empty in an AngularJS expression

I need to display either a Login or Logout button based on the value of a $rootScope variable. Currently, only the Logout button is showing up in the li tag below. I have specific actions that should occur after certain events: After Logging In:- $root ...

Class methods cannot be invoked within their constructor

I'm currently facing challenges with implementing my express router. This is a "subrouter" of my main router, hence I need to extend express.Router. Here's an example of the code (simplified to include only one method): import express from "expr ...

Rendering an element in React Router Dom based on specific conditions

Starting a new project with the latest version of react-router-dom and following their recommendation to use createBrowserRouter. The goal is to display a different header based on the path parameters. Currently, I have set up an optional path parameter: ...

Retrieve Wikipedia API JSON information using jQuery

$('#searchButton').click(function(){ var searchInput = ""; searchInput = document.getElementById('test'); if(searchInput.value !== ""){ $.getJSON('https://en.wikipedia.org/w/api.php?action=query&list=search&format ...

Is there a quicker method to update the state of an array of objects?

Here is my React state example: const [questionList, setQuestionList] = useState([ { _type: "radio", answer: "", point: "", question: "", options: ["A", "B"], ...

Show image in ReactJS using flask send_file method

Using Flask's send_file function, I send an image to the client in the following way: @app.route('/get-cut-image',methods=["GET"]) def get_cut_img(): response = make_response(send_file(file_path,mimetype='image/png')) respon ...

Is there a way to iterate through objects and add new properties to them?

I am trying to achieve the following object: let newPost = { title: "Post 1", Content: "New content" } with the code below: let newPost = {}; let postData = $(".post-data").each (function(index) { newPost.title = $ ...