Find the index of an element in a MongoDB collection

I have a set of files in the following format:

{
  "user": { "username": "string" }
  "points": 123
}

My goal is to determine a user's position within the set.

collection.aggregate([
    { $sort: { points: -1 } }, // arrange by points descending
    { 
        $project: {
            points: '$points'
            position: {
                $indexOfArray: [ 
                    '$', // I'm unsure what value should go here
                    { 'user.username': 'myUser' }
                ]
            }
        }
    }
]);

How can I handle the set as an array?

The desired output is:

[
  {
    "points": 123,
    "position": 1
  }
]

Answer №1

One way to accomplish this task is by conducting a self lookup within the data. The query below demonstrates how we can obtain the desired result:

db.collection.aggregate([
    {
        $match:{
            "user.username":"B"
        }
    },
    {
        $lookup:{
            "from":"my_collection_name",
            "let":{
                "score":"$score"
            },
            "pipeline":[
                {
                    $match:{
                        $expr:{
                            $gt:["$score","$$score"]
                        }
                    }
                },
                {
                    $group:{
                        "_id":null,
                        "above":{
                            $sum:1
                        }
                    }
                }
            ],
            "as":"selfLookup"
        }
    },
    {
        $unwind:{
            "path":"$selfLookup",
            "preserveNullAndEmptyArrays":true
        }
    },
    {
        $project:{
            "_id":0,
            "score":1,
            "rank":{
                $cond:[
                    {
                        $eq:["$selfLookup.above",null]
                    },
                    1,
                    {
                        $sum:["$selfLookup.above",1]
                    }
                ]
            }
        }
    }
]).pretty()

Data set:

{
    "_id" : ObjectId("5d657d2d7d0ab652c42315f3"),
    "user" : {
        "username" : "A"
    },
    "score" : 123
}
{
    "_id" : ObjectId("5d657d2d7d0ab652c42315f4"),
    "user" : {
        "username" : "B"
    },
    "score" : 122
}
{
    "_id" : ObjectId("5d657d2d7d0ab652c42315f5"),
    "user" : {
        "username" : "C"
    },
    "score" : 121
}

Output:

{ "score" : 122, "rank" : 2 }

Explanation: This operation involves counting the number of users whose scores surpass that of the specified user (in this case, 'B'). If no matching records are found, the rank will be 1; otherwise, it will be the count plus 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

Tips on updating all object elements in mongodb

Here is the structure I am working with: { "_id": "13hu13o13uuo1", "profiles": { "1": [1,2,3], "847891": [3, 4], .. } } The "profiles" section represents an "object-array" or d ...

Processing message received from Node JS Server

Currently, I am working on a project that involves compiling a specific Java file on the server side. In case there are any errors during compilation, I aim to capture the error information and relay it back to the client side. However, despite trying vari ...

Make sure to wait for the VueX value to be fully loaded before loading the component

Whenever a user attempts to directly navigate and load a component URL, a HTTP call is initiated within my Vuex actions. This call will set a value in the state once it has been resolved. I am looking to prevent my component from loading until the HTTP ca ...

Unable to access properties of an unknown item (reading 'remove')

Can you provide guidance on how to remove the top-level parent element of a div? I've been attempting to delete the main parent element of a specific div. element.innerHTML = ` <div class="postIt-item"> <div class="postIt-item-btn ...

MongooseError: The operation `tweets.insertOne()` exceeded the buffering timeout of 10000ms

I am facing a challenge while trying to create a basic CRUD app using mongodb and express. Despite my efforts, I keep encountering an error during the creation process. I have attempted various solutions such as altering the DNS server settings and allowin ...

Locate the largest variance among elements within an embedded object array

Imagine you have a collection of products structured as follows: { "_id" : ObjectId("5a594f8eff9da13c9d415a63"), "productId" : "xxx", "date" : "2018-09-13", "prices" : [ { "country" : "en", "price" : 16.5, ...

The d3.js Time Scale Chart is facing issues when rendering with Array object values, unlike static values which render the chart perfectly

Generating an Array Dynamically with N objects from a JSON File var taskArray = []; d3.json("input.json", function(error, json) { if (error) return console.warn(error); for ( var i = 0; i < json.length; i++) { ...

What is the process for updating IDs and names for duplicated elements?

I have created a select box and used the clone function to generate dynamic select boxes. However, the cloned select boxes have the same ids and names as the original. How can I change the ids and names of the cloned elements in my code sample below: < ...

Unique MongoDB aggregate returns tailored for your needs

Exploring MongoDB for testing purposes has been a fascinating journey. I have successfully translated some basic MySQL queries into MongoDB syntax, but now I face a more intricate challenge. The query at hand determines if there was a message within a spe ...

Unexpected behavior: jQuery AJAX request isn't triggering the alert function as expected

I can't figure out why this code isn't working: $.get("/some/url/", function(event) { alert('hey'); }); When I click the button, I can see the response being executed in the Firefox console, and it shows a successful status (200 O ...

Do Firefox and Chrome yield different results when using navigator.geolocation.getCurrentPosition()?

I need assistance with a code snippet that I have. It involves the following: navigator.geolocation.getCurrentPosition(function(position) { // do something }); However, I am encountering differences in the result returned between Chrome and Firef ...

I set up a website where every page had a consistent header using the HTML tag <head> <!--#include file="header.shtml"--> </head>, but out of nowhere, the Bootstrap functionality

I created a website with a common header that is included on all pages, but suddenly Bootstrap stopped working. What should I do now? Below is the code that was working fine previously but suddenly stopped yesterday: I have tried various solutions like r ...

Proper way to link another class in typegoose (mongoose) and store only the reference (ObjectId)?

When attempting to save certain fields in ObjectId only in the mongo db, I encountered an issue with the code below: @ObjectType() export class User { @prop() @Field() name: string; @prop({ ref: () => OtherClassA }) @Field() otherClassA: Ot ...

JQuery - Triggering mouseenter/hover event only on top-level menu items, excluding the nested submenu items (list items that are not within nested lists)

I have a complex navigation menu structure with nested lists, and I'm struggling to trigger an event only on the top-level items when hovered. Despite trying different jQuery selectors and methods, such as using the NOT selector or targeting direct ch ...

Does running npm install automatically compile the library code as well?

I have a query regarding npm and its functionality. I also posted the same question on Reddit, but haven't received a satisfying answer yet. Let's use the jQuery npm package as a case study. Upon running the command npm install jquery, I notic ...

Tips for using the Enter key to shift focus to the next input field

I am trying to move to the next input field when I hit the enter key. I found a solution in another question here, but the code provided doesn't work for me because my input fields are inside a table. Here is my HTML code: <form action="#"> < ...

Submit an image to Digital Ocean Space with Expo

I have been attempting to utilize the output image from the takePictureAsync function and upload it to a Digital Ocean Space using Expo. The uploading process with signed PUT URL appears to be functioning correctly, but I am encountering issues during the ...

Step back one iteration within the Array.prototype.map method

Can you reverse an iteration step in JavaScript when using Array.prototype.map or Array.prototype.forEach? For instance, if the current index is 2, is it possible to go back to index 1 within these methods? While we can easily achieve this with a standar ...

Utilizing JavaScript to implement an interactive :hover pseudo-class dynamic effect

After reviewing a question on adding a hover class to an element, I am now curious about how to do the opposite. I already have a main class for a button I am planning to create, where I will customize the background for each button using myButton.style.b ...

Alter the navigation background when moving between sections on a one-page website

I need to ensure that the background of the navigation remains transparent on the "home" section. However, when switching to other sections, the background color of the navigation becomes permanently black. <header class="clearfix"> <nav> ...