Modify records within MongoDB using a custom JavaScript function

In my MongoDB collection, I have documents that are structured as follows:

{
    "gran": "Day",
    "dix": NumberInt(80),
    "y": NumberInt(2017),
}, 
{
    "gran": "Month",
    "dix": NumberInt(3),
    "y": NumberInt(2017),
}

I am looking to enhance these documents by adding a from/to field, resulting in the following format:

{
    "gran": "Day",
    "dix": NumberInt(80),
    "y": NumberInt(2017),
    "from": ISODate("2017-03-21T00:00:00.000+0000"),
    "to": ISODate("2017-03-21T23:59:59.000+0000")
},
{
    "gran": "Month",
    "dix": NumberInt(3),
    "y": NumberInt(2017),
    "from": ISODate("2017-03-01T00:00:00.000+0000"),
    "to": ISODate("2017-03-31T23:59:59.000+0000")
}

To achieve this, I created a JavaScript function that translates granularities into dates:

function(year, index, gran) {
    // Function logic here
}

For updating the documents with the from/to fields, I initially attempted using this method:

db.reports.findAndModify({
  query: { "from": {$exists: false}},
  update: {
      $set: {
            "from": new Date(),
            "to": new Date()
        }
    },
  multi: true
})

Upon exploring further options, I tried utilizing the following approach:

db.reports.aggregate([
{
  $match:
  {
  } 
}
]).map(function(doc) {
  // Mapping logic here
})

However, the above method did not yield the desired results of dynamically updating the documents within the collection. Any suggestions on how I can effectively apply the script I developed for document updates?

Note that I am working with MongoDB version 3.2 and unable to upgrade to version 3.4 at this time, ruling out the use of $addFields in an aggregation pipeline.

Answer №1

After some testing, it seems like I may have found a solution that works for the limited data set I am currently working with.

db.media_code_reports.aggregate([
{
  $match:
  {
  } 
}
]).map(function(doc) {
  var dates = dateIndexToDateWithFromTo(doc.y, doc.dix, doc.gran);
  doc.from = dates.from;
  doc.to =  dates.to;
  db.media_code_reports.save(doc);
})

However, I have reservations about the efficiency of this method. It requires two steps to add the fields:

  1. Initially adding them using the findAndModify(...) function
  2. Followed by an aggregation with an empty match to retrieve all documents and then utilizing a JavaScript map() function to iterate through each document and save() the changes.

If anyone has a more efficient suggestion, I welcome your input. Otherwise, I will take this as the answer for now.

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

What could be causing my site's PDF generation process to block other AJAX processes?

I am working on an MVC3 application that needs to generate extensive reports regularly. Users can select their criteria and request the report, which currently opens in a new tab/window using the Javascript window.open() method. However, while the report i ...

Building a dynamic and fast Vite project using "lit-ts" to create a visually appealing static website

I recently put together a project using Vite Lit Element Typescript and everything seemed to be running smoothly on the development server. However, when I tried running npm run build, only the compiled JS file was outputted to the /dist folder without any ...

Performing matrix manipulations using Mirror.js (Three.js)

I am currently working on creating water effects in three.js and I haven't come across any examples in three.js that incorporate both reflection and refraction. If you know of any examples, please feel free to share the links with me. Currently, I am ...

Submitting values using the serialize method and Ajax involves sending placeholders

Looking for a solution: <form class="pure-form pure-form-stacked" method="post" enctype="multipart/form-data"> <input type="text" name="name" class="button-size-1" placeholder="*Name"> <input type="text" name="email" class="but ...

How to display a three.js scene in the center of a container

I'm having trouble getting my three.js scene to display above some cards and right below my navigation bar. Currently, the scene is rendering under the cards and is not centered. Despite looking at other forum posts for help, I can't seem to figu ...

Error: 'str' type does not have the 'strftime' attribute during conversion in ComplexDateTimeField

I'm currently working on writing a test case for a service, but I've encountered some issues. Below is an excerpt of the code I am using: datetime_one = mongo.ComplexDateTimeField()._convert_from_string('2019, 12, 20, 19, 24, 10, 451923&ap ...

What is the method for setting a condition within the setState function?

I used if for the title: in SetConfirmDialog, but it's not working. How can I fix this? <Button color={user.active ? "success" : "error"} variant="text" startIcon={<UserCheck />} title={user.active ? &quo ...

Upgrade your Angular template to templateUrl by utilizing Components

Currently utilizing Angular 1.5.7 with component structuring, I am seeking a way to display loading html while the component is loading from the server. The following code does not meet my desired outcome. I wish for the loading html code below to be visi ...

Submit information with Ajax in multipart/form format

Here is the HTML code I have: <form:form name="vcfForm" id="vcfForm" method="post" enctype="multipart/form-data" action="../acquaintance/readingContactsFromVcfFile"></form:form> <input type="file" name="vcfFile" id="vcfFile" form="vcfForm" ...

Scroll bar in Highstock does not completely cover the entire length when dealing with multiple series

Having trouble with the scrollbar on a multi-series line chart where the x-axis represents dates. It seems that the maximum length of the scrollbar is determined by the length of the first, older series. When clicking the 'All' button in the ran ...

When triggered by a click, the function gradually fades in and out. It superimposes one image on top of another, but unfortunately, the sizes

Due to different screen sizes, the image does not appear on top of another image exactly. It seems like a new function is needed. One that does not overlap with another image (by clicking the function for a few seconds), but rather replaces it for those fe ...

How to manually insert data into a Mongodb field when creating a document using Mongoose

I tried following the Mongoose documentation to create two documents, but I am facing an issue with populating one document with the other. Even after manually setting the 'account' value to reference the other document, the database does not se ...

There seems to be an issue with your SQL syntax that is preventing the data from being entered correctly into the database using Node.js, MySQL, and Express

After successfully displaying data from my database, I attempted to add data to it using the following code snippet: exports.tambahData = (req, res) => { var keyy = req.body.keyy; var valuee = req.body.valuee; var brand = req.body.brand; ...

What is the best way to trigger a jQuery function when an option is selected from a Select2 dropdown menu?

I have implemented Select2 for custom dropdown styling. The options are structured like this: <option value="001,100">Option 001</option> <option value="002,200">Option 002</option> <option value="003,300">Option 003</opti ...

What is the best way to retrieve data and handle error messages using the fetch API in Node.js?

I am attempting to utilize Node's 18 fetch API to send requests to a REST server. Below is the code snippet: const get = () => { let response = await fetch("10.0.0.12/test", { method: "GET", }); console.log(&quo ...

What is the best way to prevent users from clearing the value attribute of an input element?

Sample Scenario: While a user is entering information into a field, I would like to restrict the ability to delete or clear out the value, such as keeping "Friend" intact. Can this be accomplished using CSS or JavaScript? ...

Move the option from one box to another in jQuery and retain its value

Hey guys, I need some assistance with a jQuery function. The first set of boxes works perfectly with the left and right buttons, but the second set is not functioning properly and doesn't display its price value. I want to fix it so that when I click ...

How to transform a file into a uInt8Array using Angular

Looking to implement a feature where I can easily upload files from Angular to PostgreSQL using a Golang API. In my Angular component, I need to convert my file into a uInt8Array. I have managed to convert the array, but it seems to be encapsulated in som ...

Promises do not yield an array of objects

I am currently working on a project that involves using AngularJS with Firebase. In order to retrieve data from Firebase, I have implemented the following code snippets. Controller.js $scope.load_msg=function(){ $scope.msg=[]; Chat.load_msg($scope.na ...

there is a function nested within the render() method

While I understand how to manage the context of this inside a function, none of the suggested solutions seem to work in my scenario, and I keep encountering this is undefined The issue arises when I have a function within the render() method, and I am ...