Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
mongoose/mongodb: organiza los documentos en orden descendente según el índice de un documento, colocando el resultado en una matriz

mira este esquema por ejemplo:

 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

Lo que quiero obtener es una matriz como esta:

result = [{_id: "idB", theItem: 500}, {_id: "idA", theItem: 400}, {_id: "idC", theItem: 200}] (con solo los 10 primeros, por ejemplo)

¿Puede alguien ayudarme con esto?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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)

para obtener más información sobre la sort : https://mongoosejs.com/docs/api.html#query_Query-sort

Si busca paginación u operador de skip , consulte este documento: https://www.mongodb.com/docs/manual/reference/method/cursor.skip/#pagination-example

Actualizar

Si desea obtener resultados ordenados por el campo del elemento, simplemente reemplace sort({'_id':'desc'}) con sort({'theItem':'desc'})

 const first10Sorted = Model.find({}).sort({'theItem':'desc'}).limit(10);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!