Algorithm for maximizing storage capacity in MongoDB databases

I'm currently facing a challenge in implementing a query that is straightforward in functional programming languages but proving to be tricky in a Mongo Query.

The term I've come across for this scenario is "Max Hold":

  • I attempted to use a mongo aggregation query and utilize $function, however, it seems to only apply to calculations of the map-reduce kind (struggling to retain intermediate values within the documents being passed on)

input:

[
  { "key": 1, "value": 10 } ,
  { "key": 2, "value": 11 } ,
  { "key": 3, "value": 9 } ,
  { "key": 4, "value": 12 } 
]

output:

[
  { "key": 1, "value": 10, "prefix_max_val": 10 } ,
  { "keyquot;: 2, "value": 11, "prefix_max_val": 11 } ,
  { "keyquot: 3, "value": 9, "prefix_max_val": 11 } ,
  { "key&qout;: 4, "value": 12, "prefix_max_val": 12 } 
]

In Javascript (or any other general-purpose programming language), my approach would resemble something like this (an algorithm with linear time complexity):

function(input) {
    let result = [];
    let curr_max = 0;
    for (let i=0; i<input.length; i++) {
        result[i] = Math.max(curr_max, input[i]);
        curr_max = result[i];
    }
    return result;
}

Thank you :)

EDIT:

  • I am operating with Mongo v0.39

Answer №1

Experience the power of setWindowFields in MongoDB 5.0

db.collection.aggregate([
   {
      $setWindowFields: {
         sortBy: { key: 1 },
         output: {
            prefix_max_val: {
               $max: "$value",
               window: { documents: ['unbounded', 'current'] }
            }
         }
      }
   }
])

Visit Mongo Playground to test it out!

If you haven't upgraded to MongoDB version 5.0 yet, here's an alternative approach:

db.collection.aggregate([
   { $sort: { key: 1 } },
   { $group: { _id: null, data: { $push: "$$ROOT" } } },
   {
      $set: {
         data: {
            $reduce: {
               input: { $range: [0, { $size: "$data" }] },
               initialValue: [],
               in: {
                  $concatArrays: ["$$value", [
                     {
                        $mergeObjects: [
                           { prefix_max_val: { $max: { $slice: ["$data.value", { $add: ["$$this", 1] }] } } },
                           { $arrayElemAt: ["$data", "$$this"] }]
                     }]
                  ]
               }
            }
         }
      }
   },
   { $unwind: "$data" },
   { $replaceWith: "$data" }
])

Answer №2

If you want to determine the highest value possible, this code can be utilized:

db.collection.aggregate({ $group : { _id: null, prefix_max_val: { $max : "$value" }}});

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

Establish map boundaries using the longitude and latitude of multiple markers

Utilizing Vue, I have integrated the vue-mapbox component from this location: I've made sure to update the js and css to the latest versions and added them to the index.html: <!-- Mapbox GL CSS --> <link href="https://api.tiles.mapbox.com/m ...

How can one effectively manage event handling for dynamically generated HTML elements?

Handling events for items already present in the document is straightforward: $(document).ready(function() { $('.element-in-question').on("event", function (event) { //do what you need to do during the event }); }); But what abo ...

Error processing Discord JS command

Lately, I've been coding a moderation bot using Discord.JS and have successfully implemented various commands like Purge, Mute, etc. However, while working on the 'ban' command, I encountered an issue where the bot was not responding at all. ...

Can we invoke a function through Ajax?

Apologies for my lack of experience, I am just getting acquainted with Ajax. Please bear with me if my question seems unrefined. I attempted to do something, but unfortunately, I did not achieve success. Let me explain what I was trying to accomplish: I ...

Where is the location of the directory on the hard drive that was created using the getDirectory() method in HTML5?

I have been working on creating, deleting, and reading directories but I am unsure of where they are located on the hard drive. fs.root.getDirectory('something', {create: true}, function(dirEntry) { alert('Congratulations! You have succes ...

Slow rendering occurs with unthrottled range input, even with proper throttling applied

I'm currently seeking some general guidelines because I'm unsure where to turn for help at the moment. The issue I am facing involves an uncontrolled input[type=range] slider that performs very slowly when there are numerous steps (works fine wi ...

Guide on displaying data from MongoDB using Node.js

When working with PHP, it is simple to output data from a MySql database and structure the result with HTML attributes using a query like this: $query = "SELECT * FROM files ORDER BY ID DESC"; $response = mysql_query($query); while($row = ...

Blank area located at the bottom of the document

I'm having trouble designing a webpage without a scroll bar because there isn't much content to display on the page. I've tried searching for solutions and following steps to fix the issue, but I haven't had any success. If anyone can a ...

When I use `myState` in `Console.log`, the entire array is displayed. However, when I use `myState

As a novice in the realm of React, I am currently working on an Attendance-System Project and grappling with some messy code, my apologies in advance. Within this project, there exists a component named ShowData which receives certain props from its paren ...

Include links to external CSS and JS files within an Angular 2 component

To exclusively use "Bootstrap Select" in my.component.ts, I attempted the following approach: @Component({ templateUrl: 'my.component.html', styleUrls: [ 'my.component.css', //Bootstrap Select 'https:/ ...

In JavaScript, split the array containing both first and last names into separate variables for first and last name

Looking for a solution to split an array element in a web template, where the size of the array varies per page. The array is in the format: ['John gray','Matt jones', 'Frank white']. The goal is to separate this array into tw ...

Executing JavaScript after uploading a file using Kendo Upload and Form in MVC

Currently, I am faced with a challenge while trying to submit a form that includes a List of files as one of its properties. Upon successful completion of the ActionResult, I need to display a success message using Javascript. When I utilize Ajax.Begin f ...

"Enhance your Angular experience with SweetAlert integration using directives and translation

Currently, I am utilizing the Angular implementation of the SweetAlert plugin from GitHub. I am attempting to pass an Angular directive with translation to the title. The variable being passed as the title is: {{ 'register.confirmation_modal.SUPERI ...

"Encountered a type error: The .join method is not recognized as a function

Hello everyone, I've encountered an issue that has me a bit stumped. I recently took over a project and found a problem in which the previous developer was attempting to join an array of strings. Unfortunately, when I try to build the project, I keep ...

The HTTP request seems to be malfunctioning

When attempting to establish a connection and retrieve data from a PHP file using an AJAX request, it's important to note that the AJAX JS is located on a different website. Here is the script being used: var quer; try { quer = new XMLHttpRequest( ...

The image data is not displaying in the $_FILES variable

I am having an issue updating an image in my database. I have a modal that loads using jQuery. When I click on the save modification button, all the form data appears except for the image file, which does not show up in the $_FILES array in PHP. I have tri ...

Ensure that the content remains at the center of the screen, but is dynamic and changes

I have a unique concept I want to experiment with, but I'm unsure of the best approach to take. My idea involves centering content on the screen and instead of having it scroll off and new content scroll in, I would like it to stay centered and smoot ...

Unable to save the date as the beginning of the day in Mongoose

When storing a date in MongoDB using Mongoose and Moment.js, I encounter an issue. I am creating the date object from a date string in the format MM/DD/YYYY. Here is how I assign the date: const startDate = momentTz( data.startDate, "MM/DD/YYY ...

Creating secure neo4j nodes through a web page using Java/HTML forms: A step-by-step guide

My goal is to develop a webpage that allows users to create profiles through a form, with the form data sent to my server to generate nodes in neo4j. I am focused on preventing unauthorized commands from being sent to my server, such as via injection metho ...

Encountering a Null Pointer Exception when using MongoDB Aggregation with Spring Data and Dynamic Fields

Here is a sample code snippet of my Mongo Pojo along with getters and setters: @CompoundIndex(name = "account_date_idx", def = "{'account' : 1, 'date' : 1}", unique = true) @Document(collection = "agent_data_storage") public class Agen ...