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

228
Vistas
MongoDB updateOne gets the oldest document I want the newest

Sorry for asking this really basic question but I really want this code to work.

In node.js I update my mongo database successfully using the .updateOne() function and I keep the parameters blank as shown below. I thought it would update the most recently added document of the collection however it changes the oldest one.

How can I update the most recently added document in the collection without cycling through the entire collection? Any advice helps and I am open to using another function but would prefer not to.

the "important part":

var collection = db.collection('SensorValues');

collection.updateOne({}, { $set: { "VSWR": 999 } }, function (err, result) {
    console.log("Look I updated something");
});
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Just use db.collection.findOneAndUpdate() rather than db.collection.updateOne() adding the third argument option returnNewDocument: true.

returnNewDocument When true, returns the updated document instead of the original document. Defaults to false.

See more at https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/

over 4 years ago · Santiago Trujillo Denunciar

0

Solved!!!! Its pretty easy if you don't override the _id that mongo provides each document in a collection. All you have to do is: - Keep the filter option blank - Set sort to _id:-1

Here is my solution:

var collection = db.collection('SensorValues');//change as needed
		
		//NOTE: {} and sort{_id:-1} both return the newest document 
		collection.findOneAndUpdate(
		   	{},
   			{$set:{"VSWR":0,"updatedAt":finalid}},//change as needed
   			{
    		 sort: {_id:-1},
   			}
		);

I haven't tested it out on anything but the most recent version of Node.js but I hope it helps.

over 4 years ago · Santiago Trujillo 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