Get the highest value of a key within a nested document on MongoDB

considering the sample document below

{
  "user_id": "user 1",
  "log":[
     {
        "index" : 1,
        "position" : 50
     },
     {
        "index" : 2,
        "position" : 70
     },
     {
        "index" : 3,
        "position" : 60
     }
   ]
},
{
  "user_id": "user 2",
  "log":[
     {
        "index" : 1,
        "position" : 150
     },
     {
        "index" : 2,
        "position" : 570
     },
     {
        "index" : 3,
        "position" : 60
     }
   ]
},

how do I fetch the user_id with the highest recorded position and its corresponding index in the mongo shell? For this example, the expected outcome should be:

  1. user_id="user 2"
  2. position = 570
  3. index = 2

Appreciate your help!

Answer №1

Execute the aggregate command in order to $unwind the log array within each document and then proceed to $sort the resulting documents by their position:

db.test.aggregate({$unwind: '$log'}, {$sort: {'log.position': -1}}, {$limit: 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

I keep encountering the issue "auth is not a function" every time I try to call my authentication function within a route

Whenever a user requests sensitive information from the backend, I need to call an authenticated function. However, I am facing an issue where this function is not running when called. Below is the code for my authentication function: const auth = (req,re ...

Updating the index of an array in MongoDB using Node.js proves to be a challenging task

Currently, I am working on creating an API for a bus ticketing system. However, I am facing difficulties in getting it to function properly in Node.js. [ { "id":1, "hour" : "7:30am" , "seats" : [ 0 , 0, 0, 0, 0 , 0, 0, 0, 0 , 0 ...

What is the best way to incorporate autoplay video within the viewport?

My objective is for the video to automatically start playing when it enters the viewport, even if the play button is not clicked. It should also pause automatically when it leaves the viewport, without the need to click the pause button. <script src=& ...

I'm struggling to understand why the `Logger` class isn't available during my exploration of a JavaScript Mixin pattern guide

Currently, I am delving into the world of programming and stumbled upon this tutorial. While following along, I encountered an issue in the console displaying the error message ReferenceError: Logger is not defined --> }(Logger)). It seems that the disc ...

Transform a String into an Array object

There is a string that resembles the following pattern: var stringArray = "[[1,2,3,4],[5,6,7,8]]" The objective is to use Javascript to convert it to the following format: var actualArray = [[1,2,3,4],[5,6,7,8]] What would be the method to accomplish ...

The absence of shapes in containers is noticeable in the stage setting

After spending some time troubleshooting the issue, I have encountered a problem with my code on JSFiddle Code. My goal was to place one large container on the stage that contains two smaller containers, each holding a shape. However, despite no errors bei ...

Why are XAxis categories appearing as undefined in tooltip when clicked?

[When clicking on the x-axis, the values go from 0 to 1. I need the x-axis categories values to display on click event. When hovering over the x-axis value, it shows properly, but clicking on the x-axis does not show the correct values] Check out this fid ...

Determine the specific row number that the user clicked on within the table

I came across this code that apparently retrieves the number of the row that was clicked, but I am having trouble grasping how it works. Could someone please provide an explanation for the following code? <html> <head> <title&g ...

Clear existing markers from the map before inserting new markers

I have a map where initially the markers load coming from the database, Then there is a time-based Ajax request that fetches new records every minute. In my code snippet, I am using setMapOnAll(null) following the guidance from the Google Maps Documentati ...

What causes Docker Mongo to reject connection while building an image?

I am currently working on creating a Docker image with a running mongodb instance that already contains some data. Here is how I set up my Dockerfile: FROM mongo:3.4 RUN mongo --eval "printjson(db.serverStatus())" However, when I tried to build the i ...

Retrieving the size of every image with ajax while also storing extra image information

In my current project, the objective is to iterate through all images on a webpage and collect various details such as image name, original dimensions, actual size, ratio, display property, and FILESIZE. However, I have encountered a hurdle in my progress ...

Comma styling in JavaScript

What is the reasoning behind developers choosing to format commas in code this particular way? var npm = module.exports = new EventEmitter , config = require("./lib/config") , set = require("./lib/utils/set"); As opposed to this formatting style? va ...

JavaScript Regular Expression Assistance Domain Snatcher

I am in the process of developing a JavaScript Regex and I am struggling to find the right pattern to match a specific domain. Let me provide an example for better understanding. I need a regex that can identify any domain that exclusively contains (text. ...

Passing props from a Higher Order Component (HOC) to child components in next.js using get

I am looking to implement an HOC (Higher Order Component) for pages within my application that can provide some information stored in local storage, especially when the pages are not being server-side rendered. The challenge I'm encountering is that ...

The minimum and maximum limits of the Ionic datepicker do not function properly when selecting the month and day

Recently, I have been experimenting with the Ionic 2 datepicker. While the datepicker itself works perfectly fine, I've run into some issues when trying to set the min and max properties. <ion-datetime displayFormat="DD-MM-YYYY" [min]="event.date ...

Inside the Promise.then() function, iterate through the values using a for loop

I am curious about the behavior of promise.then() within a for loop in node.js. Consider the following code snippet: const arrayObject = [ { id: 1234, toto: 'abc' }, { id: 5678, toto: 'def' }, { id: 910, ...

Unable to display label in form for Angular 2/4 FormControl within a FormGroup

I'm having trouble understanding how to: Use console.log to display a specific value Show a value in a label on an HTML page Display a value in an input text field Below is my TypeScript component with a new FormGroup and FormControls. this.tracke ...

The $scope variable is missing from the DOM

I've been trying to implement ng-repeat with AngularJS, but I'm having trouble getting the scope result in my DOM. Is there something wrong that anyone can spot? I've spent hours troubleshooting this and no matter what I do, "players" always ...

What is the CSS method for altering the color of a slider's runnable track upon selection?

Seeking assistance in changing the slider track color upon selection. Struggling to achieve the desired outcome of altering the color as it slides. CSS: /* Custom Styles */ .text-size-slider { line-height: 100%; font-size: 14px; position: relative ...

What is the method to verify if a pop-up browser window has completed its loading process?

There is a link on my website that opens a new window. However, sometimes the new window takes so long to load. To prevent users from clicking on the link before the new window finishes loading, I want to disable it until then. I am aware that one way to ...