Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
Get last document in MongoDB collection

I am trying to get the last document in a MongoDB collection. The following works in the Mongo shell:

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

Results in the last object like so:

{ "_id" : ObjectId("62c8817075c9400469b1fc3a"), "token" : "135e53ebb05aa2b6055513843cb8e0dca1", "createdAt" : ISODate("2022-07-08T19:11:44.730Z"), "updatedAt" : ISODate("2022-07-08T19:11:44.730Z"), "__v" : 0 }

But this does not work in my Express app:

 const last = FM_Model.find().limit(1).sort({$natural:-1})
 console.log('Last Token from MONGODB here -> ', last)

In the code above the console.log returns a very long object related to the collection itself, but not the document I want.

I have tried other variations but nothing has worked so far. If anyone can give me any ideas of what I am missing that would be great.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Try

db.collection.find().sort({'_id':-1}).limit(1)

First revert the order then get the first one

about 4 years ago · Juan Pablo Isaza Denunciar

0

.find() returns an array. But there is an better version with .findOne wich return the result or undefined

FM_Model.findOne({}, {}, { sort: { 'createdAt' : -1 } })

With -1 you get the oldest element, wich is the latest.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda