2

I've Just started to work with MongoDB, so you might find my question really stupid.I tried to search a lot before posting my query here, Any Help would be Appreciated.

I also came across this link StackOverFlow Link, which advised to apply .sort() on every query, but that would increase the query time.

So I tried to index my collection using .createIndexes({_id:-1}), to sort data in descending order of creation time(newest to oldest), After that when I used the .find() method to get data in sorted format(newest to Oldest) I did'nt get the desired result , I still had to sort the data :( .

// connecting db 
mongoose.connect(dbUrl, dbOptions);
const db = mongoose.connection;

// listener on db events
db.on('open', ()=>{console.log('DB SUCESSFULLY CONNECTED !!');});
db.on('error', console.error.bind(console, 'connection error:'));

// creating Schema for a person
const personSchma = new mongoose.Schema(
{        name: String, 
        age : Number}
)

// creating model from person Schema
const person = mongoose.model('person', personSchma);

// Chronological Order of Insertion Of Data
// {name: "kush", age:22}
// {name: "clutch", age:22}
// {name: "lauv", age:22}

person.createIndexes({_id:-1}, (err)=>{
    if (err){
        console.log(err);
    }
})

person.find((err, persons)=>{
    console.log(persons)
    // Output 
    // [
    //     { _id: 6026eadd58a2b124d85b0f8d, name: 'kush', age: 22, __v: 0 },
    //     { _id: 6026facdf200f8261005f8e0, name: 'clutch', age: 22, __v: 0 },
    //     { _id: 6026facdf200f8261005f8e1, name: 'lauv', age: 22, __v: 0 }
    //   ]

})

person.find().sort({_id:-1}).lean().limit(100).then((persons)=>{
    console.log(persons);
    // Output 
    // [
    //     { _id: 6026facdf200f8261005f8e1, name: 'lauv', age: 22, __v: 0 },
    //     { _id: 6026facdf200f8261005f8e0, name: 'clutch', age: 22, __v: 0 },
    //     { _id: 6026eadd58a2b124d85b0f8d, name: 'kush', age: 22, __v: 0 }
    //   ]
})

1 Answers1

0

Indexes are special data structure, which can be used to run the queries efficiently. While running the query, MongoDB tries to see which index should be used for running the query efficiently and then that index will be used.

Creating an index with {_id:-1} will create an auxiliary data structure(index) which will be sorted newest first. It doesn't affect the order of the data which we are storing.

To sort the data in descending order(newest first) we will have to explicitly add the sort operation in your query and make sure that an index for descending order _id is present.

Deepak Patankar
  • 3,076
  • 3
  • 16
  • 35