Add a new element to an array of sub-documents. Surprising results observed

I have been attempting to add a new field to each sub-document within all arrays of sub-documents. My script is partially working, but instead of inserting the ordinal_number into every sub-document, it seems to only be adding it to the first sub-document in each comments array in the collection.

db.posts.find({
"comments.ordinal_number":{"$exists":true}}).forEach(function(data){
   for(var i = 0; i < data.comments.length; i++) {
     db.posts.update(
    { 
         "_id": data._id, 
         "comments.body": data.comments[i].body
     },
     {
         "$set": {
           "comments.$.ordinal_number":
               1
         }
     },true,true
    );
  }
});

output result:

    "link" : "cxzdzjkztkqraoqlgcru",
        "author" : "machine",
        "title" : "arbitrary title",
        "comments" : [
            {
                "body" : "...",
                "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d48ebb869bbda68c9a94a0bc819ab983b98dfab7bbb9">[email protected]</a>",
                "author" : "Foo bar",
                "ordinal_number" : 1
            },
            {
                "body" : "...",
                "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5431150d200504322e143f020e171e3a31227a373b39">[email protected]</a>",
                "author" : "Foo baz"
            }
]

Answer №1

To achieve maximum efficiency, it is essential to loop through the cursor and array entries while utilizing the $ operator to update each sub-document in the array using "bulk" operations.


var bulk = db.posts.initializeOrderedBulkOp();
var count = 0;
db.posts.find().forEach(function(doc) { 
    var nComments = doc.comments.length; 
    for (var i = 0; i < nComments; i++) {
        bulk.find( { 
            '_id': doc._id, 
            'comments': { '$elemMatch': { 'email': doc.comments[i]['email'] } }
        } ).update({
            '$set': { 'comments.$.ordinal_number': 1 } 
        }) 
    } 
    count++;
    if(count % 200 === 0) {   
        // Execute per 200 operations and re-init
        bulk.execute();     
        bulk = db.posts.initializeOrderedBulkOp(); 
     }
})

// Clean up queues.
if (count > 0)  bulk.execute();

It's important to note that the Bulk API was introduced in version 2.6. If you are working on an older version, you will need to utilize the .update() method.


db.posts.find().forEach(function(doc) { 
    var nComments = doc.comments.length; 
    for (var i = 0; i < nComments; i++) {
        db.posts.update( 
            { 
                '_id': doc._id, 
                 'comments': { '$elemMatch': { 'email': doc.comments[i]['email'] } }
            }, 

            { '$set': { 'comments.$.ordinal_number': 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

Searching for mustache variables in HTML using regular expressions is a helpful way to

As I work on parsing template files in my code, one of my first tasks involves removing all Mustache variables in the template. The majority of these variables follow this structure: {{variable}}, {{#loop}}{{content}}{{/loop}}, {{^not}}{{/not}}, {{! comme ...

Using JavaScript, what is the process for getting the value of a child node within Firebase

var ref = firebase.database().ref("games/" + gameId + "/patterns"); ref.on("child_changed", function(snapshot){ var pattern = snapshot.key; console.log(pattern); }); Currently, the code snippet above only logs the key. But how can I extract the player ...

After toggling the switch to send the current state to the server, the React state remained unchanged

Could you clarify why the relay1 state is being sent as false? Why doesn't handleControlRelay1 change the state? Am I making a mistake by placing this inside a function? setRelay1((prevValue) => !prevValue); // ... const [relaysData, setRelaysD ...

What is the best way to locate the final element within a collection in MongoDB?

In my Mongo DB Atlas database, there is a collection named Users. {"_id":{"$oid":"5ebe6fdc9f17193b6c51063e"},"name":"Harry","country":"India","gender":"male"} {"_id":{"$oid":"6fbe6fdc9f17193b6c52463e"},"name":"John","country":"Africa","gender":"male"} {"_ ...

Steps to send an asynchronous AJAX request to the server-side within the JQuery validation plugin using the addMethod() function

Currently, I am in the process of developing my own framework using the JQuery validation plugin to validate CRUD forms both client-side and server-side. It is crucial that these forms are not static but rather created dynamically using "handlebar.js". Fo ...

What is the method for displaying an image within an HTML div element?

Is there a way to include an image inside an HTML div tag when printing a document? Here's the method I've been using: Using HTML5: <div> <img src="/images/pag.jpg" alt="pagsanghan Logo" style="opacity: .8; height:100px; width:10 ...

Display the intersection of two objects in varying colors using three.js

Is there a way to display the overlapping volume of two objects in THREE.js using different colors or textures? I want to be able to show the combination of the two objects with a unique color, like purple for example if the original colors are red and blu ...

Why do images show up on Chrome and Mozilla but not on IE?

I have tested the code below. The images display in Chrome and Mozilla, but not in IE. The image format is .jpg. Can someone please assist? bodycontent+='<tr class="span12"><td class="span12"><div class="span12"><img class="span ...

Issues encountered when implementing server-sent events in a project built with Node.js and React

I've been working on implementing server-sent-events into my Node.js and React application. After doing some research and following tutorials online, I found this particular site to be very helpful and straightforward. The main objective is to have a ...

Tips on accessing a browser cookie in a Next.js API endpoint

I've set a cookie in the layout.js component and it's visible in the browser. Now, I need to be able to retrieve that cookie value when a post request is made to my API and then perform some action based on that value. Despite trying different ...

Comparing the distinction between assigning values to res and res.locals in a Node.js application using Express

Greetings! I am inquiring about the utilization of res (Express response object) and res.locals in Express. During my exploration of nodejs, I came across a code snippet that consists of a middleware (messages.js), a server (app.js), and a template (messa ...

The parent element of a 3D div is causing issues with hovering and clicking on the child elements

In my scenario, the parent div is transformed in 3D with rotation, causing it to move to the backside. The issue arises with the child div containing a button that becomes unclickable due to the parent div position. Setting backface-visibility to hidden al ...

Bootstrap modal not displaying in full view

I recently ran into some issues while using a jQuery plugin with my bootstrap modal on my website. After implementing jQuery.noConflict(), I encountered a problem where the program no longer recognized $, forcing me to replace all instances of it with jQue ...

What is the procedure for incorporating JavaScript into my tic-tac-toe game's HTML and CSS?

I have created a simple Tic Tac Toe game using HTML and CSS. Although there is no embedded Javascript, I do reference a Javascript file for functionality. Can anyone provide me with the most straightforward Javascript code that will display an 'X&apos ...

Striving to implement a dynamic dropdown menu using React's <select> element and rendering users from an array as selectable options

I am currently working on a project to develop an application that allows users to be added to a MongoDb database and have their names displayed in a dropdown menu. While creating the form, I encountered two issues - one related to the closing tag error a ...

JavaScript: Struggles with utilizing a function as an argument and later executing it inside a nested function

I've been struggling with defining a new function, and I need help resolving it. Here's an example that I was initially referencing: Pass arguments into ajax onreadystatechange callback? I wasn't able to find the solution through research, ...

Pre-requisites verification in TypeScript

I have a typescript class with various methods for checking variable types. How can I determine which method to use at the beginning of the doProcess() for processing the input? class MyClass { public static arr : any[] = []; // main method public stati ...

Strategies for extracting MongoDB collection information from a MySQL database table

When working with Yii2, I am attempting to retrieve data from a Mongo collection field within a MySQL table using DB activerecord. The structure of my summary table/model is as follows: 'merchant_id' => '123' 'report_date ...

Issues with using hooks in a remote module in Webpack 5 module federation

I am attempting to create a dynamic system at runtime using Module Federation, a feature in webpack 5. Everything seems to be working well, but I encounter a multitude of 'invalid rule of hooks' errors when I add hooks to the 'producer' ...

Using jQuery's AJAX function to send a POST request and extracting data from the response

Below is the jQuery AJAX call that I am using: $.ajax({ method: "POST", url: "/Agenda/Template", dataType: 'json', data: { "templateId": templateSelect.options[templateSelect.selectedIndex].value }, c ...