Updating an array within an object using JSON

Check out the structure of my JSON response:

"_id" : 537,
    "quizzes" : [
        {
            "wk" : 1,
            "score" : [
                10
            ]
        },
        {
            "wk" : 2,
            "score" : [
                8
            ]
        },
        {
            "wk" : 3,
            "score" : [
                5
            ]
        },
        {
            "wk" : 4,
            "score" : [
                6
            ]
        }
    ]
}

I'm attempting to make changes to the score array within one of the objects. Take a look at what I've done:

db.collection('connect').update({_id: id}, {$push: { quizzes[0]: { score: 89  }  }});

Answer №1

Here is the suggested update to try:

db.collection("connect").update(
    {
        "_id": id            
    }, 
    {
        "$set": { 
            "quizzes.0.score.0": 89    
        }
    }
);

This approach utilizes the dot notation for accessing array elements and fields within an embedded document.

To access a specific element in an array using its zero-based index, simply concatenate the array name with a dot (.) followed by the zero-based index surrounded by quotes:

'<array>.<index>'

Answer №2

It appears that you are searching for

db.collection('connect').update({_id: id}, {$set: { "quizzes.0.score":89}  })

An improved approach would be to avoid relying on the index of the quizzes array and utilize the "wk" attribute instead

db.collection('connect').update({_id: id,quizzes:{$elemMatch:{"wk":1}}}, {$set: { quizzes.$.score: 89  }  }})

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

experimenting with a TypeScript annotation

I have created a simple decorator that can trigger either stopPropagation() or preventDefault() based on certain conditions. I have thoroughly tested this decorator in my application and am confident that it works correctly. However, I encountered an issue ...

Implementing Partial Login and Registration Views using AngularJS in conjunction with MVC5 and ASP.NET Identity

Embarking on the journey of creating a Single Page Application with log-in/register functionality using MVC5, ASP.NET Identity, and Angular feels like diving into a vast ocean of web development technologies. Despite being new to this realm, I delved into ...

Using Regular Expressions in JavaScript to verify if an element from an array is contained within a string

Looking for a simple JavaScript code for a Vue application that will split the string into an array and check if any value is present in a different string. Here's what I have: let AffiliationString = " This person goes to Stony Brook" ...

Restoring the position of the <Rect/> element after dragging in a React + Konva application

In my attempt to make a Rect component snap back to its original position using ReactKonva, I defined a Toolbar class with certain dimensions and initial positions for the rectangle. However, after dragging the rectangle and attempting to reset its positio ...

Learn the method of conditionally resetting the state count using React hooks

When a user submits the form, the handleSubmit function runs to count the number of li elements with class names containing "show" within the search results div. It adds up these counts using setStoreCount(prevCount => prevCount + 1) and updates the UI ...

JavaScript Regular Expression for separating a collection of email addresses into individual parts

I am very close to getting this to work, but not quite there yet. In my JavaScript code, I have a string with a list of email addresses, each formatted differently: var emailList = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...

Establishing global date restrictions for the DatePicker component in Angular 8 using TypeScript across the entire application

I am currently learning Angular 8 and I am looking to globally set the minimum and maximum dates for a datepicker in my application. I would like to accomplish this by using format-datepicker.ts. Any suggestions on how I can achieve this? Min date: Jan 1, ...

Load components in NextJS lazily without utilizing `next/dynamic`

Currently, I am in the process of developing a component (Editor) that should always be lazy-loaded in React applications. However, I need it to be compatible with any React app. While I have successfully implemented lazy loading with Create React App usi ...

What steps should I follow to enable a tooltip in this specific situation using qtip?

In my database, I have tables for venues, venue types, and map icons with the following relationships: A venue belongs to a venue type A venue type belongs to a map icon Each venue result is shown on the index page as a partial. Each partial ...

onpageshow event behaves as expected exclusively on webkit browsers (triggers function solely when visible on the screen)

I am inserting an HTML file using an object tag. The encompassing div of the object tag is hidden with a display:none property. However, I encounter an issue where the onpageshow event that I placed on the body tag of the HTML object behaves differently a ...

Are HTML's Regular Expressions the Equivalent of JavaScript's Regular Expressions?

I have been trying to utilize the pattern="" attribute in HTML to implement regex, but unfortunately, I am unable to locate a comprehensive list of HTML regex parameters. This has led me to ponder whether the syntax for regex in HTML is similar to JavaSc ...

The signin callback in NextAuth doesn't seem to be activating as expected

I recently integrated the Google provider into my next js project using next auth and mongoDb. When a user signs in with Google, various fields like {name, email, id , image, emailVerified} are automatically saved to the users collection in the database an ...

Ways to retrieve the identifiers of every child node UL element within a UL container

I am struggling with a basic question related to HTML structure. Here is the code snippet I am working with: <ul> <li> <ul class=t2 id=15> <li class='item'>a<span class='val'>b</ ...

Add a new component to a Vue.js instance that is already in use

Just getting started with Vue.js I'm looking to register a local component following the instructions here: https://v2.vuejs.org/v2/guide/components.html#Local-Registration The catch is that I need to register the component to an existing Vue insta ...

Breaking circular dependencies in JavaScript is a common challenge that developers face when

Having encountered a circular dependency issue between certain JS files, I am seeking steps to resolve it. Q1: Is repositioning the require function an appropriate solution? One suggested approach to resolve this issue is to move the require() statement ...

There was an error parsing the data from the specified URL (http://localhost:8000/src/client/assets/data.json

Hey there, I'm a newcomer to Angular and I'm having trouble reading a JSON array from a file. Every time I try, it gives me a "failed to parse" error. Can someone please provide some guidance? Here is my folder structure: src --assets ---a ...

What is the size limit for JSON requests in Node.js?

I am seeking information about the req object in nodeJS. Let's say I have a code that sends data in JSON format to my server using an AJAX POST method. Now, imagine a scenario where a user manipulates my client code to send an excessively large JSON f ...

Ways to insert a line break within a jQuery function using text()

I am looking to add a new line in my jQuery function. $.ajax({ url:"http: //192.168.1.4/Experiements/webservices/api.php", type:"GET", dataType:"json", data:{type:"login", UserName:userId,Password:userPassword}, ...

Searching and adding new elements to a sorted array of objects using binary insertion algorithm

I'm currently working on implementing a method to insert an object into a sorted array using binary search to determine the correct index for the new object. You can view the code on codesanbox The array I have is sorted using the following comparis ...

Locate all the properties that are empty within each object contained in a JavaScript array

Consider this scenario: if I were to have an array of JavaScript objects like the following: var jsObjects = [ {a: 1, b: 2, c: null, d: 3, e: null}, {a: 3, b: null, c: null, d: 5, e: null}, {a: null, b: 6, c: null, d: 3, e: null}, {a: null, ...