I must utilize the MongoDB native driver to retrieve unique IDs sorted by a timestamp column

I am currently utilizing the nodejs mongodb native driver for developing a chat application. Within my database, I have a collection named dialog which contains fields for sessionId and dateCreated (timestamp). My objective is to retrieve a list of distinct sessionIds ordered by their latest (max) dateCreated timestamp, with a limit of 20 records.

Below is my current implementation:

db.collection('dialog').distinct('sessionId',
        function(err, users){
            if(users.length > 10){
                users = users.slice(0, 20);
            }
            console.log("users: " + users);


        });

Here are a couple sample documents from the collection:

{ 
  "sessionId" : 455206183, 
  "msg" : "hi what's up?", 
  "dateCreated" : ISODate("2015-02-05T20:17:55.418Z"), 
  "_id" : ObjectId("54d3cff30e3ddb6922fbc2bb") 
}, { 
  "sessionId" : 163220612, 
  "msg" : "yo", 
  "dateCreated" : ISODate("2015-02-05T20:18:00.434Z"), 
  "_id" : ObjectId("54d3cff80e3ddb6922fbc2bc") 
}

Answer №1

In the feedback provided, it has been suggested that in order to obtain the desired results, an aggregate function may be necessary. The following code snippet could potentially help achieve this:

db.dialog.aggregate([
    { $sort: { "$dateCreated": -1, "$sessionId": 1 }},
    { $group: { _id: "$sessionId", dateCreated: {$first: "$dateCreated"} }},
    { $limit: 20 },
    { $project: { sessionId: 1, _id: 0 }}
]);

This script initially sorts the collection based on dateCreated and sessionId, then groups them by unique session IDs while selecting the latest $first date created for each group. Afterwards, it limits the output to 20 entries and presents an array of objects with only the sessionId values included.

Please bear in mind that I have not personally tested this code snippet, so feel free to provide feedback on its performance.

Answer №2

Following Olli K's advice really helped me find the right path. It turns out that sorting after grouping by works perfectly.

db.collection('dialog').aggregate([
        {$group: {_id:"$sessionId", dateCreated: {$first: "$dateCreated"} }},
        {$sort: {"dateCreated":-1}},
        {$limit: 20}],
function(error, users){
    //do something
});

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

Wait for the reaction from react router history to go back

After clicking the submit button in a form, I need to navigate backwards using history.goBack. However, if there is no previous page in the history, I want to redirect to a screen displaying a thank you message using history.replace. const handleSubmit = ( ...

Arranging three DIVs in a row with the middle one having a scrolling feature to view its

I have the following sections in my layout: 1) Header, 2) Left Panel, 3) Middle Div1, 4) Middle Div2, and 5) Right Div <div id="HEADER"> </div> <div id="LEFT_PANEL"> </div> <div id="DIV1_mid"> </div> <div id="DIV2 ...

Ways to increase the count in Vue Class Bindings?

Trying to utilize Vue class bindings, but uncertain about the syntax for bindings. I aim to append a numeric value to the class attribute, for instance class = "allstar50", then employ class bindings with the v-for directive to display a list of text items ...

A tool that showcases outcomes determined by the interaction of two variables

I have two select inputs: <select id="inputA"> <option>1</option> <option>2</option> <option>3</option> </select> <select id="inputB"> <option>1</option> <option>2</opti ...

Multiple tabs open with inactive sessions

I am currently facing an issue regarding user idle timers in jQuery. I have implemented a timer that logs the user out of the app if they are inactive for 30 minutes, and this works perfectly with one browser tab open. However, I now need to extend this ...

Having trouble sending data from a React application to a Node.js server using the fetch method

Currently, I am utilizing fetch to send data from the React side to Node.js (both running on my localhost), and this is how I am implementing it: let formData = new FormData(); formData.append("agent_name", this.state.agentName); formData.append("a ...

Navigating the complexities of large relationships in a MongoDB many-to-many structure

After going through numerous documentation and examples on Stackoverflow, I'm still uncertain about my conclusions, which is why I'm seeking help. Let's consider a scenario where we have two collections - Films and Users. We want to determi ...

Learn how to create a web application by utilizing HTML5 and REST, and then seamlessly transfer the front-end code to a mobile app using Cordova

Can a mobile application be developed from a web portal using Cordova or similar frameworks? The web portal will consist of: HTML5 for front-end J2EE for back-end with JAX-RS Is it feasible to extract pages from the web portal and integrate them into a ...

Desiring to iterate through an array of identification numbers in order to retrieve information from an external API

I have been working on an app where I retrieve IDs from one API and pass them into a second API to display the property overviewList.overview.lifeTimeData.energy for each ID. However, in my current setup, I am only able to display the property of the fir ...

Removing the _id field from a collection in MongoDB

I am aware that it is not feasible to delete the _id field from a mongodb collection. However, due to the large size of my collections, the index on the _id field is causing issues with loading other indices into RAM. My machine has 125GB of RAM and the st ...

Interact with various div elements bearing the same class name through mouse movements

I am trying to implement a mousemove effect on multiple divs with the same class name but facing an issue where the mouse position doesn't restart inside each div. If you want to see a demo of what I'm describing, click here. Below is the code ...

Is it possible to utilize Jquery in order to add an opening <tr> tag and a closing </tr> tag within a dynamic table?

I have been experimenting with the code snippet below in an attempt to dynamically add a closing </tr> tag followed by an opening tag after every three cells, essentially creating a new row. Progress has been made as the DOM inspector shows a TR nod ...

Long-term responsibilities in Node.js

Currently, I have a node.js server that is communicating between a net socket and a python socket. The flow is such that when a user sends an asynchronous ajax request with data, the node server forwards it to Python, receives the processed data back, and ...

There are errors occurring in the getter I created within the vuex store.js file

Currently utilizing vuejs, vuex, and vuetify. Within this project there are 3 files in play and I will share the key sections here. The main objective is to showcase data associated with the route parameter. Despite my attempts in Product.vue as shown bel ...

Ways to navigate a div within an iframe that has been loaded

As I load a page(A) inside an iframe, the HTML structure of the embedded content is as follows: <html><body> <div id="div1"></div> <div id="div2"><button>Hello</button></div> </body></html> The ...

Is it possible to transmit audio from two separate sources through a single peer via WebRTC technology?

Is there a way to send both the microphone audio and an audio file on separate tracks using a single stream in JS? ...

Inputting spaces instead of line breaks in the text area

Hello everyone, I have a challenge with adding line breaks in a textarea using jQuery and HTML. I am loading dynamic content into the textarea using $.load() but in Internet Explorer, the newlines are not displaying when I use tags, , or . I h ...

One click activates the countdown timer, while a second click on the same button pauses it

How can I create a button that allows me to start the countdown timer on the first click and pause it on the second click? I want both functionalities in the same button. Here is an image for reference: https://i.stack.imgur.com/fuyEJ.png I currently ha ...

"The magic of ReactJS's virtual DOM lies in its ability to keep a lightweight representation

Stumbled upon this statement in some form while browsing the web Whenever the data underlying a React application changes, a new Virtual DOM representation of the user interface is generated. This is where things start to get interesting. Updating the b ...

Notifier - The Best HTML Notification System for Web Applications

Currently, I am developing a notification system using Play Framework 2.3 (Java) in combination with MySQL. The system is designed to retrieve notifications from a "notifications" table stored in MySQL database. I initially attempted to use AJAX polling ...