Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!