Sort before returning documents in Mongo Query and Mongoose pagination

I have an array inside my schema that creates timestamps for each array index created. I am trying to sort my documents so that the most active timestamp inside each function gets displayed first when returned from the find function. But the issue I am having is that I am using Mongoose Pagination and it only returns 10 documents at a time.

Example:
Let’s say I have documents of the user’s login information and inside each document, I have an array that stores every timestamp when they login. When calling the find function, I want to pass a query that goes through each selected document and retrieve the most updated timestamp from that specific array.

Hi @Jon_Paricien,

Can you describe the pagination problem a bit more? If you have an array inside a single document containing the information you need, the entire array should be returned with the single document, preventing the need to paginate.

If you’re looking specifically for the most recent timestamp within an array of a single document, you can use aggregation with $project and $reduce to provide only the most recent timestamp from the array.

Thanks,

Justin

2 Likes

I’ve tried this but I am not getting the results correctly. How can I combine the $filter function with $reduce?

Hi @Jon_Paricien,

Do you have any examples of data and your desired result? I’ll need some sample data and examples of what you’ve attempted to help.

Thanks,

Justin

With your help, I was able to figure out the problem. Thank you @Justin