retrieve records in reverse chronological order with mongodb

In my project, I am inserting a large amount of historical data documents into a history collection. Since these documents are never modified, the order remains correct as no updates are made. However, when retrieving the data, I need them in reverse order.

To retrieve the data in pages of 20 records, I am using the following code:

var page = 2;

hStats_collection.find({name:name},{_id:0, name:0}).limit(20).skip(page*20).toArray( function(err, doc) {
});

After researching, I found that using $sort is not the best solution. It seems the most effective way to reverse the order of data retrieval in the code above is to create an index using a timestamp element in the document. I have a useful element called started (seconds since epoch) that I can use to create the index.

http://docs.mongodb.org/manual/tutorial/create-an-index/ The documentation suggests creating an index like this:

hStats_collection.createIndex( { started: -1 } )

How can I modify my .find() code above to include the name field and reference the started index so that the results are returned from newest to oldest (instead of the natural oldest to newest order)?

Answer №1

hStats_collection.find({username:username},{_id:0, name:0})
.sort({ timestamp:-1 }).limit(20)

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

Retrieve information from various MongoDB collections

Greetings! I currently have a database with the following collections: db={ "category": [ { "_id": 1, "item": "Cat A", }, { "_id": 2, "item": "Cat B" ...

Iterating over objects within a nested array using ng-repeat

My back-end is sending me an array of string arrays (Java - CXF-RS). The length of each array within the string arrays ranges from 1 to n. In order to display this data on my front-end, I am utilizing ng-repeat. Everything is functioning correctly with o ...

MongoDB failing to utilize a single field index in aggregation operations

I have a dataset with a field named country that is indexed, and I want to count the number of documents per country using the following query: db.collection.aggregate([ {"$group" : {_id:"$,country", count:{$sum:1}}} ]) The query p ...

Confusion surrounding the Mongodb Java 3.0 driver

I am currently working with the Java 3.0 MongoDB driver, and attempting to utilize the distinct feature. When using the deprecated DBCollection, I was able to execute the following: collection.distinct("tokens.account_id", new BasicDBObject("_id",new Obj ...

Is there a way to dynamically assign column names during the import process?

In my current scenario, I am importing data from various sources into my JSON backend. The mapping file will resemble the sample below. The question is how can I efficiently utilize this mapping during data import into my backend. The idea is to provide t ...

Search the table for checked boxes and textboxes that are not empty

Could you suggest alternative ways to express the following scenario? I have a table with 3 rows. Each row contains a column with 3 checkboxes and another column with just a text box. I would like it so that when the values are retrieved from the database ...

Struggling to convert mongoengine documents to JSON using Django and only receiving arrays of field names

Here is the model I am working with: class Estados(Document): Nome = StringField(max_length = 20, required=True) Sigla = StringField(max_length = 2, required=True) Cidades = ListField(StringField) When I execute a query using this method: fr ...

Executing a jQuery function only once per click on a select element - how can it be done?

I have a form with a select element, and I want some code to run when I click on it, but not when I choose an option. The issue is that the code is running twice, preventing me from selecting an option as it resets itself each time. Here is the HTML: &l ...

Highcharts real-time data not refreshing following modification of PHP variable

Currently, I have a live updating highchart implemented on a webpage named index.html. This highchart calls a PHP script called datatest.php to parse a CSV file, convert the data into JSON format, and then add it as a new point on the chart: $.ajax({ ...

Is it possible to reference a .js file within an HTML file using AngularJS?

Having a slight issue with an email function. I experimented with the 'nodemailer' package and successfully sent an email when coding in a .js file. Upon calling the .js file (node emailfile.js), the email was received as expected (code provided ...

What is the significance of the error message '[WDS] Disconnected!' in the context of using webpack and Vue.js?

Currently, I am engaged in a Django project that utilizes Vue.js for the frontend. Whenever I refresh the page, I encounter the "[WDS] Disconnected!" error. Despite the website's full functionality and absence of issues, this error appears every time ...

Choose a procedure to reset to the original setting

I'm attempting to achieve something that seems straightforward, but I'm having trouble finding a solution. I have a <select> tag with 5 <option> elements. All I want to do is, when I click a button (which has a function inside of it), ...

How can I use jQuery to access the parent node in an XML document?

I have been trying to extract the top-level 'label' attribute from the XML code below using jQuery, but I haven't had any luck so far. I have already converted it into a DOM object, but the results are not what I expected. Does anyone have a ...

Error: Missing responseText in Jquery

Struggling with accessing ajax response data? I have encountered an issue with my ajax request that sends Json to a server and the response returns Json as well. Even though I receive the response, I am unable to access the responseText. Below is the code ...

What is the process for isolating characters from a variable?

Is there a way to extract the first character up to 1 character after the decimal point? I am receiving data from an API {POWER : 1343.45} {POWER : 15623.34577} {POWER : 123.434} I only require 123.4 from 123.45, 15623.3 from 15623.34577, etc. How can I ...

Is there a method to track the progress of webpage loading?

I am working on a website built with static HTML pages. My goal is to implement a full-screen loading status complete with a progress bar that indicates the page's load progress, including all images and external assets. Once the page has fully loaded ...

Error in the syntax containing ?callback=jQuery1113

I'm attempting to initiate a simple JSONP query: <html> <head> <script type="text/javascript" src="js/jquery1.js"></script> <script> $(document).ready(function(){ $.ajax({ ...

It appears that the JavaScript global dynamic variable is undefined as it changes from function to function, suggesting it might be

I'm encountering an issue with the way these two functions interact when used in onclick calls of elements. Due to external circumstances beyond my control, I need to keep track of when and how elements are hidden. Everything works perfectly as inten ...

Setting the initial scroll position in a ReactNative ListView after the data has been loaded

I need a solution for jumping to specific dates in an events section, with the initial scroll position set to the first future date. To achieve this, I have attempted to store the y positions of each date in the state. renderSectionHeader= (sectionData, ...

Understanding the mechanisms of Promise functionality within Typescript can be challenging, particularly when encountering error messages such as "type void is not

Recently, I've delved into the world of Typescript. Despite my efforts to stay true to the typing system, I've encountered a challenge that forces me to resort to using the any type: The issue arises with a function that returns a promise: sav ...