Let's say I have some records as below:
{
id: 1,
age: 22,
name: 'A',
class: 'Y'
},
{
id: 2,
age: 25,
name: 'B',
class: 'D'
},
{
id: 3,
age: 30,
name: 'C',
class: 'Y'
},
{
id: 4,
age: 40,
name: 'D',
class: 'B'
}
Now I need to get the last (closest) record which has an age less than 28. For this, I can use the following code:
const firstUsersYoungerThan28 = await Users.find({
class: 'C',
age: {
$lt: 28
}
})
.sort({
age: -1
})
.limit(1)
.lean();
const firstUserYoungerThan28 = firstUsersYoungerThan28[0];
Let's say the collection have millions of records. My question is, is this the most efficient way? Is there a better way to do this?
My biggest concern is, does my app load the records to the memory in order to sort them in the first place?