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

118
Views
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 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)

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 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!