Modify the array in a MongoDB document using a specific index variable

Is there a way to update a specific index in an array within a mongoDB document using a variable?

{
    _id: 'IDString',
    field: [ bla, bla, old, bla ];
}

let i = 2;
Collection.update(
    { _id: 'IDString' },
    { $set: 
        { 'field.$.i': 'new' }
    }
);

This should result in:

{
    _id: 'IDString',
    field: [ bla, bla, new, bla ];
}

I attempted to incorporate the variable i, but my code did not produce the desired outcome.

Answer №1

To efficiently update an element of an array using the dot notation syntax, concatenate the array name with the zero-based index position enclosed in quotes. This dynamic approach allows you to set up your update document accurately.

For instance, if we consider a scenario where you need to update the third element of an array named "field", the update document would look like this:

var update = { "$set": { "field.2": "new" } }

The code below demonstrates how to achieve this dynamically:

var i = 2,
    update = { "$set": {} };

update["$set"]["field."+i] = "new";
db.collection.update({ "_id": "IDString" }, update)

Answer №2

Updating a collection with MongoDB:
Collection.update(
    { _id: 'IDString', field.2 : 1 },
    { $set: {
        "field.$" : "new value" }
    }
)

If you encounter any issues, please leave a comment.

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

I encounter difficulty utilizing assets within my React application

Currently, I am in the process of developing a React application for practice purposes. However, I have encountered an issue with using images and audio files stored in the assets folder. Despite my attempts to import them into the project, I have been uns ...

What is preventing me from viewing the index name that mongodb is using?

db.tablebusiness.find({ "LongitudeLatitude" : { "$nearSphere" : [106.772835, -6.186753], "$maxDistance" : 0.053980478460939611 }, "Prominent" : { "$gte" : 15 }, "indexContents" : { "$all" : [/^soto/, /^nasi/] } }).limit(200).explain(); { "curso ...

Injection of Angular state resolve into controller fails to occur

I'm attempting to ensure that the value from ui-router's resolve is successfully passed to the controller portalsForUserCtrl. Take a look at the router code below: (function () { 'use strict'; var myApp = angular.module("myApp", ["co ...

Obtaining the initial row information from jqGrid

If I use the getRowData method, I can retrieve the current cell content instead of the original data before it was formatted. Is there a way to access the original content before any formatting transformations are applied? Just so you know, I am filling t ...

Controlling factory JSON data with $http calls using two separate controllers

I'm attempting to retrieve a JSON response from a factory, save it as a variable, and make it accessible from two different controllers. Below is the code I am utilizing: storyFactory.js var story = angular.module('story.services', []); ...

Pass the retrieved object back to the calling function in NodeJS using asynchronous MySQL operations

I'm diving into NodeJS for the first time and struggling to create a reusable function that can execute a query passed as a parameter and then return the response to the caller. This approach is necessary as there are over 100 functions in need of dat ...

Ways to time animations differently and activate two animations at the same time in every loop

I have 3 hidden text boxes that I want to fade in and slide down simultaneously by 40px when the DOM loads. They should be staggered so that each one triggers after the previous animation finishes. Below is the relevant JavaScript code snippet: jQuery(fu ...

Is null a type of object in JavaScript?

As I delve into the realm of JavaScript data types, I stumbled upon a peculiar discovery: > typeof null "object" > null instanceof Object false At this point, I am baffled as to how to make sense of this phenomenon. I was under the assumption that ...

How can one iterate through elements of a specified length using Jquery?

Currently, I am in the process of designing an animation for my website. The animation involves different divs that each contain an image and a description related to that image within an aside element. The width of the aside is slightly wider than the ima ...

MongoDB query result customization with user-defined fields

Having been accustomed to SQL, I encountered a dilemma while working with mongoDB, particularly using mongoose. The issue at hand involves a collection named User. var UserSchema = new Schema ({ id : ObjectId, name : {type : String, trim : true, ...

Transforming NIF to OBJ within the Blender 249.2 software results in an object that is not visible

I am currently utilizing Three.js for rendering Fallout 3 assets in WebGL. Check out the JavaScript code for a similar object rendering here. Most objects are loading fine along with their normals, except for the brahmin... While the texture and normals a ...

Complicated conditional query in mongodb to find a matching value if it exists

I am currently exploring the possibility of implementing a condition that requires some answers on whether it can be achieved or not. Imagine I have a collection called: Restaurant Restaurant id name food Now, let's assume I have 4 rows: 1, resta ...

"Looking to dynamically adjust attributes within a popover using JavaScript in Bootstrap 5? Let me show you how

I have been attempting to utilize JavaScript to set an HTML attribute in a popover within Bootstrap 5, but I am encountering difficulties. Below is the code snippet for the popover: <button type="button" class="btn btn-secondary mx-3&quo ...

Automatically injecting dependencies in Aurelia using Typescript

Recently, I started working with Typescript and Aurelia framework. Currently, I am facing an issue while trying to implement the @autoinject decorator in a VS2015 ASP.NET MVC 6 project. Below is the code snippet I am using: import {autoinject} from "aure ...

I am interested in scraping a webpage, how should I go about it?

Similar Questions: How to create a web crawler? Top techniques for parsing HTML I've always been curious about accomplishing a task like this. Although I do not own or manage the website (), the information I am interested in is publicly acce ...

Fetching works flawlessly in the local environment, but encounters issues when deployed

Fetching Data Problem in Vercel Deployment vs Localhost I'm encountering a problem with fetching data in my React app. Here's a simplified version of the code snippet: useEffect(() => { async function fetchData() { const res = await fet ...

Verify the checkboxes in one row

How can I create a table row that will automatically generate data from SQL and bind it using backend code? Is there a way to check if the user has clicked on it using JavaScript? The row is created as shown below: <tr> <td align="right" cl ...

Is it possible to update the state before initiating an API call that relies on that specific state in React?

useEffect(() => { resetState(); if (page === 'ADMISSION') { fetchAdmissionKitPosts(); } else if (page === 'WEEKLY') { fetchWeeklyKitPosts(); } else if (page === 'FESTIVAL') { fetchFestivalK ...

Exploring Angular 2 Beta 8: An Introduction to @Query Usage

My attempt to utilize @Query to fetch data regarding an element in my template has not been successful. I made an effort using the following approach: Referenced here. Here is a snippet of my code, import {Component, Query, QueryList, ElementRef} from &a ...

The backend and frontend both operate smoothly individually, so why is it that the frontend is unable to load backend data on Vercel

Today, I deployed both my frontend and backend on Vercel. Before this, there was an error (not 404) in the backend. However, after someone on Stack Overflow suggested changing the root file from server.js to index.js, I made the change and the backend star ...