Refine your MongoDB collections with multiple filtering options

My dataset looks like this:

[
    {"userId": "0000", "algorithm": "algo1", "status": "Running",   "waitingTime": 0},
    {"userId": "0001", "algorithm": "algo1", "status": "Received",  "waitingTime": 0},
    {"userId": "0000", "algorithm": "algo2", "status": "Completed", "waitingTime": 123},
    {"userId": "0000", "algorithm": "algo2", "status": "Error",     "waitingTime": 134},
    {"userId": "0001", "algorithm": "algo2", "status": "Error",     "waitingTime": 150},
    {"userId": "0001", "algorithm": "algo3", "status": "Completed", "waitingTime": 100},
    {"userId": "0000", "algorithm": "algo3", "status": "Completed", "waitingTime": 120},
    {"userId": "0001", "algorithm": "algo1", "status": "Received",  "waitingTime": 0}
]

I am seeking the maximum waiting time for each user, only when the status is set to "Completed". The desired output should include 2 properties per entry.

  • "_id" - matching the "userId" field from the original collection
  • "maxWaitingTime" - indicating the highest waiting time among "Completed" entries

In this case, the expected output should be:

[
    {"_id": "0000", "maxWaitingTime": 123},
    {"_id": "0001", "maxWaitingTime": 100}
]

I attempted to combine multiple filtering queries but encountered challenges. I managed to combine one or two statements, but struggling with this particular task.

I experimented with using the distinct method along with find to obtain unique userId's, but without success:

db.tasks.distinct("userId").find();

Additionally, I tried incorporating the logic within the find function:

printjsononeline(db.tasks.distinct(userId).find({
    userId: "0001"
}).map(doc => doc));

Unfortunately, neither approach yielded the desired results.

Answer №1

Check out the Unique Playground!

db.collection.aggregate([
  {
    "$match": {//Filter completed tasks
      "taskStatus": "Complete"
    }
  },
  {
    $group: {//Grouping by user ID and finding maximum waiting time
      "_id": "$userId",
      "maxWaitTime": {
        "$max": "$waitTime"
      }
    }
  }
])

Remember: MongoDB is case-sensitive, and some prefer using waiting_time over waitingTime.

Answer №2

Utilizing aggregation is key here (check out https://docs.mongodb.com/manual/aggregation/). By using the match operator, you can filter based on status, while the group operator enables you to retrieve the highest wait time for a specific user ID.

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

The Vue feature responsible for displaying information on the webpage is currently not working as expected

I'm in the process of developing a settings page for a project. This particular page is based on HTML and utilizes JSON to store data, with Vue 3 being used to display the information on the page. However, I've encountered an issue where the data ...

Strategies for setting up the runtime dynamically for Nextjs API routes

After deploying my Next.js 13 app on Cloudflare Pages, I encountered an issue with the API routes. To address this, I had to export the runtime variable from each route in the following manner. export const runtime = "edge" During local developm ...

What would you name this particular element?

I want to create a unique slider design but I'm unsure where to begin or how to search for information because I don't know the correct terminology. Does this type of slider have a specific name? I heard about Marquee, but that seems like someth ...

Instructions for using Selenium to access the "stats for nerds" option on a YouTube video by right-clicking

I am currently working on a program that has the ability to block YouTube ads and keep track of the blocked Ad Video IDs. To achieve this, our selenium program needs to simulate a right click on the video to open the video menu and then select "stats for ...

Limit the API call to only respond to requests from the localhost

I'm currently working on a website that uses API calls within the same node project. I would like to restrict most of these API calls to only be accessible by the localhost website. Is there a way to achieve this without implementing OAuth and simply ...

Pulling a div from beneath numerous other divs

I have been attempting to create a test case for a web application we are developing and I am on the verge of finding a solution, but there is one final hurdle that has me puzzled... Our requirement is to enable div elements to be draggable (which is work ...

Utilizing Arrays for Angular Data Binding with AJAX

I am currently experimenting with loading Ajax data into an array and then binding the array using Angular. Here is my code (I have some experience with KO, so I'm keeping it simple for now): Update: I managed to get it working. I believe the issue w ...

Utilize only certain JSON properties within JavaScript

I have access to an array of JSON objects. [ { Id: "1", StartNo: "1", ChipNo: "0", CategoryId: "0", Wave: "0", Club: "", FirstName: "Lotta", LastName: "Svenström", FullName: "Lotta Svenström", ZipCode: "24231" }, {...} ] My goal is to create a new data ...

Tips for incorporating the camera from fbxloader into your three.js scene

I am currently utilizing fbxloader from three.js to incorporate a model into my scene. I have noticed that the most recent version of fbxloader.js (https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/FBXLoader.js) has the capability to read ...

Try implementing Underscore/Lodash to organize an object by values and convert it into an array of pairs that can be utilized with AngularJS ng

My goal is to showcase the details from the given object on the user interface using Angular's ng-repeat. It is essential for me to arrange the key/value pairs based on their values and exhibit them in sequential order in an array from highest to lowe ...

Tips for globally overriding MUIv4 class in JSS for nested themes

Summary: Skip to EDIT2 MUIv4 has generated the following classes for me based on my nested theming: <label class="MuiFormLabel-root-121 MuiInputLabel-root-113 MuiInputLabel-formControl-115 MuiInputLabel-animated-118 MuiInputLabel-shrink-117 M ...

Why does AngularJS $watch only execute once?

Why do the codes in the watch only run once? How can I address this issue? this.$rootScope.$watch('tabType', () => { if (this.$rootScope["tabType"] === TabType.Sent) { this.$scope.refreshSentList(); } else if (this.$rootScope[ ...

Having a concise way to submit forms with Javascript and JQuery

Seeking a more concise way to submit form data to Electron in JSON format as a beginner in JavaScript and jQuery. How can this code be rewritten for brevity? <section> <input id="server" type="text" placeholder="Server"> <i ...

Deactivating a Vue custom filter when hovering over it

I'm trying to figure out how to disable a truncate filter when hovering over an element using VueJS 2. Here's the part of my template that includes the filter: <div class="eng" @mouseover="showAll">{{ word.english | truncate }}</div> ...

Some sections of the HTML form are failing to load

I'm currently following a tutorial and applying the concepts to a Rails project I had previously started. Here's my main.js: 'use strict'; angular.module('outpostApp').config(function ($stateProvider) { $stateProvider.sta ...

What improvements can I implement to enhance the clarity and functionality of this form handler?

As a beginner working on my first Next.js app, I'm facing some challenges that seem more React-related. My app allows users to add and edit stored food items and recipes, requiring me to use multiple submit form handlers. Each handler involves: Che ...

Submitting a Yii 2 form automatically when it loads

Pjax::begin(); $form = ActiveForm::begin(); echo $form->field($model, 'testdata', [ 'inputOptions' => [ 'class' => 'form-control input-xsmall input-inline' ], ...

Effortlessly glide to the top of the webpage

After dedicating numerous hours to this task and being a newcomer to JavaScript/JQuery, I am still unsure of how to achieve the following: I have implemented a "back to top" anchor link in the footer of my pages that directs users back to the header. I am ...

Issues with concealing the side menu bar in Vue.js

I've been attempting to conceal the side menu bar, with the exception of the hamburger icon when in the "expanded" state. Despite my efforts to modify the CSS code, I am still struggling to hide the small side menu bar. The following images represent ...

Interactive pop-up messages created with CSS and JavaScript that appear and fade based on the URL query string

I have a referral form on this page that I want people to use repeatedly. After submitting the form, it reloads the page with the query string ?referralsent=true so users can refer more people through the form. However, I also want to show users a confir ...