Updating a value within a nested array in MongoDB

I am in need of updating all documents where the value inside an array inside another array ("days.Hour") is "08h" to "8".

{
"_id" : ObjectId("5bbd1396197aa5389cb7bfb7"),
"days" : [ 
    {
        "Day" : "Saturday",
        "Hour" : [ 
            "08h", 
            "10h"
        ]
    }, 
    {
        "Day" : "Sunday",
        "Hour" : [ 
            "08h", 
            "10h"
        ]
    }
],
"name" : "Guilherme",
"isActive" : true,
"gender" : "male"
}

Even though I attempted to use a foreach loop, it was not successful:

myCollection.find({}).forEach(function(doc) {
    doc.days.forEach(function(day) {
        day.Hour.forEach(function(hour) {
            hour = hour.replace("h", "");                
            print(hour);
        });
    });
    // Even if I can replace the document here, the changes do not stick
    print(doc);
});

Answer №1

Instead of manually manipulating data and writing it back for multiple documents, consider using the following query:

myCollection.updateMany({
}, { $set: { "days.$[].Hour.$[eachHour]": '8h' } }, {
    arrayFilters: [{ 'eachHour': '08h' }]
})

Collection Data :

/* 1 */
{
    "_id" : ObjectId("5bbd1396197aa5389cb7bfb7"),
    "days" : [ 
        {
            "Day" : "Saturday",
            "Hour" : [ 
                "08h", 
                "10h"
            ]
        }, 
        {
            "Day" : "Sunday",
            "Hour" : [ 
                "08h", 
                "10h"
            ]
        }
    ],
    "name" : "Guilherme",
    "isActive" : true,
    "gender" : "male"
}

/* 2 */
{
    "_id" : ObjectId("5e2f085ad02e05b69487f2b3"),
    "days" : [ 
        {
            "Day" : "Saturday",
            "Hour" : [ 
                "18h", 
                "10h"
            ]
        }, 
        {
            "Day" : "Sunday",
            "Hour" : [ 
                "08h", 
                "10h"
            ]
        }
    ],
    "name" : "Guilherme2",
    "isActive" : true,
    "gender" : "male"
}

/* 3 */
{
    "_id" : ObjectId("5e2f0865d02e05b69487f3a0"),
    "days" : [ 
        {
            "Day" : "Saturday",
            "Hour" : [ 
                "18h", 
                "10h"
            ]
        }, 
        {
            "Day" : "Sunday",
            "Hour" : [ 
                "18h", 
                "10h"
            ]
        }
    ],
    "name" : "Guilherme3",
    "isActive" : true,
    "gender" : "male"
}

Result :

/* 1 */
{
    "_id" : ObjectId("5bbd1396197aa5389cb7bfb7"),
    "days" : [ 
        {
            "Day" : "Saturday",
            "Hour" : [ 
                "8h", 
                "10h"
            ]
        }, 
        {
            "Day" : "Sunday",
            "Hour" : [ 
                "8h", 
                "10h"
            ]
        }
    ],
    "name" : "Guilherme",
    "isActive" : true,
    "gender" : "male"
}

/* 2 */
{
    "_id" : ObjectId("5e2f085ad02e05b69487f2b3"),
    "days" : [ 
        {
            "Day" : "Saturday",
            "Hour" : [ 
                "18h", 
                "10h"
            ]
        }, 
        {
            "Day" : "Sunday",
            "Hour" : [ 
                "8h", 
                "10h"
            ]
        }
    ],
    "name" : "Guilherme2",
    "isActive" : true,
    "gender" : "male"
}

/* 3 */
{
    "_id" : ObjectId("5e2f0865d02e05b69487f3a0"),
    "days" : [ 
        {
            "Day" : "Saturday",
            "Hour" : [ 
                "18h", 
                "10h"
            ]
        }, 
        {
            "Day" : "Sunday",
            "Hour" : [ 
                "18h", 
                "10h"
            ]
        }
    ],
    "name" : "Guilherme3",
    "isActive" : true,
    "gender" : "male"
}

This query updates two documents in the collection.

For more information, refer to: .updateMany()-arrayFilters

Answer №2

Give this a shot

time.Hour.forEach(function(hour){
    let updatedHour = hour.replace("h", "");                
    display(updatedHour);
})
        

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

Issue encountered: Unable to fetch username and password from request

Currently, I am developing a login and registration system. However, when I input the correct details in my register Post method, the request remains pending and I cannot identify the error. The specific error message it presents is data and salt arguments ...

Jquery function for determining height across multiple browsers

I am currently facing an issue with setting the height of table cells in my project. While everything works smoothly on most browsers, Firefox seems to add borders to the overall height which is causing inconsistency across different browsers. If anyone k ...

When anchor is set programmatically, the focus outline is not displayed

I am currently facing an issue with my application where I am programmatically setting focus on elements in certain scenarios. While it generally works well, I have noticed that when I set the focus on an anchor element using $("#link1").focus(), the focus ...

Looping through a JSON array and encoding it using the `

I am looking to retrieve data from the database using AJAX and populate a 'select' tag with that data. Each name should be displayed in its own 'option'. Here is the code snippet: Index.php: <label>Select:</label> <sel ...

"Implementing a self-invoking function in JavaScript and effectively clearing the interval within it

I am looking to stop the animation interval in this particular example $.fn.bounce = function(options) { var settings = $.extend({ speed: 10 }, options); return $(this).each(function() { var $this = $(this), $pa ...

Converting a jQuery DOM element into a string representation

Currently, I am working with a textarea that contains the contents of an HTML file. This textarea includes all elements of my HTML page such as doctype, head, html, etc. My goal is to save the content of the textarea into a DOM variable using $.parseHTML: ...

What is the best way to handle multiple JSON data using jQuery?

Understanding how to utilize jquery for parsing simple json is a valuable skill. json { "Symbol": "AAL.L", "Name": "ANGLO AMERICAN", "Last": "3061.50", "Date": "7/26/2011", "Time": "11:35am", "Change": "+3 ...

Combine arrays using underscore or lodash

Hello, I need some assistance. I have a couple of arrays containing grades with associated classes attributes like the examples below: var arr1 = [{ "id": 53, "name": "Grade 1 AppMonkeyzTest", "classes": [{ "id": 5 ...

By clicking anywhere, AngularJS will remove the specified class

Imagine having a search box that is displayed after the user clicks on a button. Great so far, right? But what if you want to add another feature - making the search box disappear when the user clicks anywhere else. How can this be achieved with AngularJS? ...

How to Enhance GraphQL Mutation OutputFields with a Function Generator

I'm encountering issues while trying to incorporate a function generator within a GraphQL mutation. The function generator is utilized to streamline the promise chain inside the mutation. Prior to refactoring the code, everything was functioning corr ...

Navigating through this object with PUG and Express: a step-by-step guide

I am currently working on a basic blockchain project to practice my skills with nodejs. I have created a blockchain object that consists of a block class, and now I want to loop through this object using pug. app.get('/', function(request, respon ...

Javascript increasing the variable

Whenever I interact with the code below, it initially displays locationsgohere as empty. However, upon a second click, the data appears as expected. For example, if I input London, UK in the textarea with the ID #id, the corresponding output should be var ...

How can I retrieve the value of an HTML component when submitting a form?

In my ExpressJS application, I have two pages: home and user. In the home.js file, I create a form that navigates to the user.js page when submitted. While I am able to retrieve values from input components, I am facing issues with other components. How ca ...

Determine the date and time based on the number of days passed

Hey there! I have a dataset structured like this: let events = { "KOTH Airship": ["EVERY 19:00"], "KOTH Castle": ["EVERY 20:00"], Totem: ["EVERY 17:00", "EVERY 23:00"], Jum ...

Issue with connect() method in React-Redux resulting in a TypeError

Currently immersed in the Redux tutorial by Dan Abramov, specifically on chapter 27 - Generating containers with connect(), encountering a rather peculiar bug: To start off, I define these two functions: const mapStateToProps = (state) => { return ...

Extract the URL of the background image from a preexisting <div> element, or append a new attribute to the background-image property

I am facing a challenge in updating the existing background-image with a linear gradient. Currently, my CMS is generating a background-image, but I am unable to adjust the opacity using a linear gradient. My goal is to darken the background-image using CSS ...

Having trouble posting data in node.js using MongoDB and EJS

Hey everyone, I'm currently working on creating a page with a form and text input fields. However, I'm encountering an error that says "Cannot Post". Here is my code, any help would be greatly appreciated. Why isn't it working? This is app. ...

JavaScript removing elements from an array

In my situation, I am dealing with "scene" and various graphics "objects"... Scene.prototype.objects=new Array(); Scene.prototype.add=function(obj){ var last=this.objects.length; this.objects[last]=obj} Scene.prototype.remove=function(obj){ this.o ...

What is the correct way to dynamically switch between RTL and LTR in React with Material UI?

I recently learned that in order to support right-to-left (RTL) languages with Material UI, you need to follow these steps. I have a select input that allows users to switch between languages, changing the overall direction of the app. The core of my appl ...

Issue: Unable to locate module - Error in integration of Vue.js with Laravel framework

I'm currently following a tutorial on YouTube for setting up Vue and Laravel. My resources folder structure looks like this so far: - resources - js - app.js - vue -app.vue In my app.js file: require('./bootstrap&ap ...