Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda