Retrieving MIN/MAX values from an array in MongoDB

I'm currently facing a challenge with executing a query to retrieve only the MIN and MAX values for a specific field within an Array field...

The field client.files.uploads is the target for fetching the MIN/MAX values.

The desired result should be something like "0,10", where I aim to extract just the lowest and highest values of uploads from all client entries without returning multiple fields or rows for each client.

Below is my initial query which did not provide the expected outcome:

db.client.aggregate([
    {$unwind: "$files"},
    { 
     $group: { 
            _id : "$_id",
            data_min: {$min: "$files.uploads"},
            data_max: {$max: "$files.uploads"}
        }
    },
    {
        $project:{
            data_min: "$min",
            data_max: "$max",
        }
    }
],{allowDiskUse:true})

UPDATE:

I have successfully achieved the desired result using a different approach, but I still believe there might be a more efficient way to accomplish this task:

db.clients.aggregate([
  {$unwind: "$files"},
  {
    $group: {
      _id: "$_id",
      data_min: {$min: "$files.uploads"},
      data_max: {$max: "$files.uploads"}
    }
  },
  {

    $group: {
      _id: "1",
      min: {$min: "$data_min"},
      max: {$max: "$data_max"}
    }
  },
  {
    $project: {
      _id: 0,
      min: 1,
      max: 1
    }
  }
],
{
  allowDiskUse: true
})

This modified query now returns a single row containing the minimum and maximum values for the entire collection, meeting the original objective.

Here is an example dataset based on my documents:

[
  {
    "name": "John",
    "files": [
      {
        "uploads": 9685,
        "downloads": 83,

      },
      {
        "uploads": 1,
        "downloads": 833
      },
      {
        "uploads": 676,
        "downloads": 823
      }
    ]
  },
  {
    "name": "Peter",
    "files": [
      {
        "uploads": 32,
        "downloads": 99
      },
      {
        "uploads": 34,
        "downloads": 4
      }
    ]
  },
  {
    "name": "Mery",
    "files": [
      {
        "uploads": 3,
        "downloads": 244
      },
      {
        "uploads": 15,
        "downloads": 543
      },
      {
        "uploads": 1345,
        "downloads": 22
      },
      {
        "uploads": 6743,
        "downloads": 87543
      }
    ]
  }
]

Answer №1

Your interpretation is incorrect. Instead of utilizing the accumulator operator as values, adjust your projection as follows:

{
    $project:{
        _id: 0,
        data_min: 1,
        data_max: 1
    }
}

Answer №2

Look at this sample aggregation query

db.clients.aggregate({"$unwind": "$files"},
                     {"$project":{"name":"$name","files":"$files"}},
                     {"$group":{"_id":"$_id","max":{"$max":"$files"},
                                             "min":{"$min":"$files"}}
                     }).pretty()

Alternatively, you can utilize $project as shown below

db.clients.aggregate({"$unwind": "$files"},
                     {"$project":{"name":"$name","files":"$files"}},
                     {"$group":{"_id":"$_id","max":{"$max":"$files"},
                                              "min":{"$min":"$files"}}},
                     {"$project":{"max_upload":"$max.uploads",
                     "max_download":"$max.downloads",
                     "min_upload":"$min.uploads",
                     "min_downloads":"$min.downloads","_id":0
                                  }
                     })

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

Prevent unauthorized access to ng-href by implementing validation measures in AngularJS

I have been struggling to find a solution for my AngularJS issue. As a newcomer to AngularJS, I am not yet familiar with all of its functionalities. I have a multi-part form that is submitted at the end using ng-href and HTTP GET. The code snippet for subm ...

What is the best way to save <div> tags to localStorage?

Currently, I am facing an issue with setting an array of items (divs) to Local Storage. My intention is for these elements to be displayed in the Ui when the page reloads. The function I have written checks if there is already an array stored with that nam ...

what is the best way to display a chosen value in a dropdown menu using jQuery?

How can I display a value from a database in a select option? This code is written in PHP, JSON, AJAX, and JQUERY. $(document).on('click', '.edit_data', function () { var shop_id = $(this).attr("id"); $.ajax({ url: "&l ...

Is it advisable to specify data types for my JSON data in TypeScript?

For the shopping application in my project, I am utilizing a JSON structure to categorize products as either hot or branded. However, I encountered an issue when trying to define a type for the entire JSON object labeled "full". Despite my attempts, it app ...

What is the best way to retrieve an array that was created using the useEffect hook in React?

Utilizing the power of useEffect, I am fetching data from two different APIs to build an array. My goal is to access this array outside of useEffect and utilize it in the return statement below to render points on a map. However, when trying to access it ...

Exploring the Client/Server model in the context of Electron (Atom Shell) usage

I'm currently grappling with understanding the inner workings of Electron (formerly known as Atom Shell). Coming from a background in traditional MVC-style web applications where a Browser interacts with a Controller Action via a Routing System, fetc ...

I'm puzzled by the "Uncaught TypeError:" error message and can't seem to figure it out

I'm having trouble displaying the value of 'true' within my objects and keep encountering an error message. Uncaught TypeError: Cannot set property 'toDoIsRemoved' of undefined at removeTask (main.js:85) at HTMLButtonElemen ...

Why is my client program not receiving a response from this socket.io server?

Currently, I am in the process of developing a trivia game where two users engage in answering questions with the winner being declared at the end. As part of this project, I have integrated socket.io to facilitate the exchange of answers. However, I have ...

Differentiating a MongoDB document into a Java class

Currently, I am utilizing the MongoDB driver within my Java code. Let's assume there is a MongoDB document stored in the collection db.people: {"name":"Joe", "surname":"Blow", "age":20} Along with a Java class structured as follows: `public class ...

Creating a Reddit-inspired voting system using Laravel 5.3 and VueJS

Currently in the process of learning Vuejs (not too experienced with Laravel), and my goal is to create a basic voting system for various tasks. I've succeeded in adding, editing, and deleting tasks. However, upon implementing the upvote/downvote feat ...

Transmit a document to the OpenAI API without the need to interact with the file storage system

Is there a way to send file data to the OpenAI API without directly accessing the file system? I have the file contents stored as a string and would like to bypass reading from the file system. The code provided in the OpenAI documentation involves reading ...

Step-by-step guide for activating a text box when a check box is marked

I'm looking to activate and deactivate two text boxes when a check box is selected. Currently, only one text box is enabled when the check box is checked. How can I modify my code to enable and disable two text boxes based on the check box status? Her ...

I am using MongoDB to manage a collection of debit/credit transactions and I need to calculate the balance for each individual

In my database, I have a collection of transactions that includes sender_id, receiver_id, and amount. { "_id": { "$oid": "55279f6c1a7f98030043ddf3" }, "sender_id": "00001", "receiver_id": "00002", "amount": 10000, "__v": 0 } By q ...

The response from the Ajax request in jQuery did not contain any content to download

I have a PHP script that generates PDF output successfully when accessed directly. Now, I want to fetch this PDF file using AJAX. In pure JavaScript, the following code snippet works well: var req = new XMLHttpRequest(); req.open("POST", "./api/pd ...

Is it possible to disable the next and previous buttons in jCarousel?

I am currently using the jCarousel slider from for my website. The slider displays one image at a time, with a total of four images. I want to hide the previous arrow when displaying the first image and hide the next arrow when displaying the fourth image ...

Press the smiley icon and drag it into the designated input box

Is there a way to select and copy a smiley/emoji from a list and paste it into an input field? Although the Inspect Element Q (console log) shows that the emoji is being clicked, I am having trouble transferring it to the input field. Here is the HTML cod ...

Conceal a div while revealing the other div

I am currently trying to achieve a unique visual effect. I have three divs named div1, div2, and div3. The objective is for div1 to slide up and disappear when clicked, while div2 simultaneously slides up and becomes visible. Similarly, when div2 is click ...

Utilizing Javascript to populate RecurrenceData in a SharePoint Calendar List

Is there a way to set RecurrenceData values in SharePoint Calendar List using Javascript? var recurreciveData = "<recurrence> <rule> <repeat> ...

I am facing an issue with Angular 14 and Webpack 5, where certain unnecessary nodejs modules seem to be hindering me from successfully serving

I have recently started working on a cutting-edge Angular 14 application. My current node version is v14.20.0, and npm version is 8.17.0. Despite my best efforts, I seem to be facing an issue with multiple nodejs dependencies being included in my project ...

Retrieve the runtime configuration object or file using Jest

Is there a way to access the Jest runtime config object or file path? I wanted to utilize runtime config properties in my custom matchers. // ./jest.config.js const path = require("path"); module.exports = { prop1: "foo", prop2: "bar" }; // my-custo ...