索引对db.find()没有影响



我刚刚开始使用MongoDB,所以你可能会发现我的问题真的很愚蠢。我试着搜索了很多之前张贴我的查询在这里,任何帮助将不胜感激。

我还遇到了这个链接StackOverFlow link,它建议在每个查询上应用。sort(),但这会增加查询时间。

所以我试着用。createindexes ({_id:-1})索引我的集合,以创建时间(最新到最老)降序排序数据,之后,当我使用。find()方法以排序格式获取数据(最新到最老)我没有得到想要的结果,我仍然要对数据进行排序:(.

// 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 }
//   ]
})

索引是一种特殊的数据结构,可以用来高效地运行查询。在运行查询时,MongoDB尝试查看应该使用哪个索引来有效地运行查询,然后使用该索引。

使用{_id:-1}创建索引将创建一个辅助数据结构(索引),该数据结构将首先进行最新排序。它不影响存储数据的顺序。

要按降序排序数据(最新的优先),我们必须显式地在查询中添加排序操作,并确保存在降序_id的索引。

最新更新