How to get the latest registration | mongoDB | Nodejs

2

I am developing a small project and I have a very simple question, if I have in DB a few records, for example these:

{
 { 'name':'nombre1',
   'edad':'22'
 },
 { 'name':'nombre2',
   'edad':'23'
 },
 { 'name':'nombre3',
   'edad':'24'
 },
}

How can I do to select the last record, which in this case would be the one with the name 'name 3'?

Thank you very much.

    
asked by Freak24 14.03.2018 в 02:15
source

1 answer

1

You can sort the records by insertion order using Natural Order and specifying that they come from the most recent to the oldest

db.micoleccion.find().sort({$natural:-1});

If you want the last record, it would be

db.micoleccion.find().sort({$natural:-1}).limit(1);

Eye : If you use the MMAP1 storage engine, the natural order considers update an existing record makes it the most recent .

    
answered by 14.03.2018 / 12:37
source