'mongoose/mongodb - Arrange documents in descending order based on a document's index, placing the result in an array

look at this schema for example:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let MySchema = new Schema({
    _id: {type: String},
    theItem: {type: Number}
})

const MySchema = mongoose.model("MySchema", MySchemaSchema)
module.exports = MySchema

What I want to get is a array like this:

result = [{_id: "idB", theItem: 500}, {_id: "idA", theItem: 400}, {_id: "idC", theItem: 200}] (with only the first 10, for example)

Can someone help me with this?



Solution 1:[1]

//To get first 10 elements 
// using `limit` you can retrieve specific number of documents
const first10 = Model.find({}).limit(10);

// To get first 10 elements sorted by `_id` in descending order
const first10Sorted = Model.find({}).sort({'_id':'desc'}).limit(10);

// If you want to get the elements from 11 to 20 next time when you query
// Using combination of skip and limit you can get the next 10 sorted records.
const next10 = Model.find({}).sort({'_id':'desc'}).limit(10).skip(10)

for more info on sort - https://mongoosejs.com/docs/api.html#query_Query-sort

If you are looking for pagination or skip operator refer to this document - https://www.mongodb.com/docs/manual/reference/method/cursor.skip/#pagination-example

Update

If you want to get results sorted by the theItem field then simply replace sort({'_id':'desc'}) with sort({'theItem':'desc'})

 const first10Sorted = Model.find({}).sort({'theItem':'desc'}).limit(10);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1