Robmongo - combine unique values based on different columns

As a newcomer to robmongo, I've been tasked with writing queries for a collection that includes keys like "userId" and "deviceModel." My goal is to create a query that shows the number of users for each device model.

Here is the query I have so far:

db.device_data.aggregate([{"$group": {"_id": "$data.deviceModel", "count": {"$sum": 1}}}])

However, this query currently only counts the number of keys for each device, not the number of users.

{
   "_id": { "$binary": "AN6GmE7Thi+Sd/dpLRjIilgsV/4AAAg=", "$type": "00" },
   "auditVersion": "1.0",
   "currentTime": NumberLong(1479301118381),
   "data": {
    "deviceDesign": "bullhead",
    "loginType": "GOOGLE",
    ...

This is an example of what one key looks like in the collection.

Answer №1

If you want to find the distinct count of userId for each deviceModel, you can use the following query. This query will only count a userId once if it appears multiple times for the same deviceModel.

db.collection.aggregate([
    {"$group" : {_id:"$data.deviceModel", userIds:{$addToSet: "$userId"}}},
    {
        $unwind:"$userIds"
    },
    {
        $group: { _id: "$_id", userIdCount: { $sum:1} }
    }
])

Unwind:-

The $unwind operator deconstructs an array field from the input documents to output a document for each element.

In the above query, the $unwind operator deconstructs the userId array created in the first pipeline.

addToSet:-

The $addToSet operator returns an array of all unique values resulting from applying an expression to each document in a group of documents sharing the same group by key.

This ensures that only unique values are added to an array. In this case, the userId is added to an array in the first pipeline.

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

Organize AngularJS ng-repeat using dictionary information

I'm dealing with a dictionary consisting of key-value pairs, which looks something like this: data = { "key1": 1000, "key2": 2000, "key3": 500 } My goal is to display this data in a table using AngularJS. One way I can achieve this is b ...

md- The datePicker component consistently encounters errors with Date instances

I encountered an issue where the error message The ng-model for md-datepicker must be a Date instance. Currently the model is a: string appeared. I am utilizing moment.js library to handle dates. Within the view section: <md-datepicker ng-model="Model ...

Inline checkbox label with Bootstrap 5 styling

How can I align the checkbox with its label? Example <div class="row g-1 border-bottom p-3"> <div class="col border-end justify-content-center d-flex align-items-center"> <div class="h6 text-sm-center h-25&quo ...

Comparing the differences between while loops and setTimeout function in JavaScript

I'm currently deciding between using a while loop or a setTimeout function in JavaScript. As I understand it, due to JavaScript's single-threaded nature, having one function run for an extended period can hinder the execution of other functions s ...

Preventing Flash of Unstyled Content in ElectronJS Browser Windows

Upon creating a new BrowserWindow and utilizing loadURL to incorporate an html file within the renderer, there is a brief instance where unstyled content is displayed for approximately half a second before the css is loaded. window.loadURL('file://&a ...

How can you use jQuery to remove a class from an element after a specified period of time?

After updating a record in the database, I plan to make modifications using an AJAX request. Once that is done, I will dynamically add a class to the rendered div by utilizing the addClass method. The class being added (we'll refer to it as colored) c ...

Searching for users with specific patterns of string using LDAP JS in Node JS

Currently, I have implemented LDAP JS for Authentication in my Angular JS application and everything is working smoothly. Now, as I am creating a new view, I have a specific requirement: There is a text box where an admin will input a few letters of a u ...

Using TypeScript with ReactJS

While working on a form using React-select, I encountered an issue when trying to pass parameters to a function. The error message returned was: Expected 1 arguments, but got 0.ts(2554) index.tsx(31, 31): An argument for 'selectRef' was not pr ...

Color scheme for navigation bar carousel item background color

I have a navigation bar and carousel within the same section. I want to change the background color of both the navigation bar and carousel item when the carousel indicator becomes active. Any suggestions on how to achieve this using a jQuery function? H ...

Live AJAX inquiries in progress

Is there a way to track the number of active AJAX requests in jQuery, Mootools, or another library similar to Prototype's Ajax.activeRequestCount? I am looking for a method that can be used across different libraries or directly through XMLHttpRequest ...

The value of the checked input with the name `nameofinput` is currently not defined

I'm having trouble passing the input value to another page. $( this ).attr( "href", '?module=module_progress_report&Subject='+ $('input[name=subject]:checked').val()+ '&Centre_Selected_ID='+ encodeURIComponen ...

The authService is facing dependency resolution issues with the jwtService, causing a roadblock in the application's functionality

I'm puzzled by the error message I received: [Nest] 1276 - 25/04/2024 19:39:31 ERROR [ExceptionHandler] Nest can't resolve dependencies of the AuthService (?, JwtService). Please make sure that the argument UsersService at index [0] is availab ...

What is the best way to create a taskbar using HTML or Javascript?

I'm currently developing an innovative online operating system and I am in need of a functional taskbar for user convenience. The ideal taskbar would resemble the Windows taskbar, located at the bottom of the screen with various applications easily ac ...

Utilize JavaScript to load external JavaScript libraries and scripts

Currently, I am working on developing a console application using JavaScript/Node.js. However, when compiling the script.js file, I encounter a ReferenceError: $ is not defined issue. //user input from command line var readline = require('readline&ap ...

Passing data between Vue.js components effortlessly without relying on events

At the moment, I am utilizing Laravel Nova. It's worth noting that it operates using vue.js. I've created a personalized vue component which requires the ability to modify data inside another component. This specific component is located in the ...

Retrieve the audio file from the server endpoint and stream it within the Vue application

I am working on a listing module which includes an audio element for each row. I need to fetch mp3/wav files from an API and bind them correctly with the src attribute of the audio element. Below is my code snippet: JS methods:{ playa(recording_file) ...

Using jQuery to extract a specific portion of a URL path

Seeking assistance with extracting category information from lengthy URLs and assigning it to a variable. Consider the following URL: http://example.com/community/home/whatever.html The goal is to assign the variable to the folder path that follows /hom ...

What is the most efficient way to retrieve key pair values of separate elements in an array with just one API request?

The API I am working with returns an array of elements, each containing multiple key-value pairs. An example of a similar API response can be seen here: , where an array of poems is returned. [ { "title": "...." "content": "..." "url" : "..." } ...

Is there a way to connect two tables using CSS pseudo-selectors?

Is there a way to make two separate tables interact with each other using CSS pseudo-selectors? I have a data table and an auto-numbered table, and I want the rows to highlight in both tables when hovering over a cell in one of them. I've tried using ...

When invoked, a Javascript Object comes back empty

My code snippet: const channels = fauna.paginate(q.Match(q.Index("channels"), "true")) // Query FaunaDB database for channel list => create constant called users containing results const channelList = channels.each(function (page) { ...