Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

//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);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda