George Faraj
George Faraj

Reputation: 43

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");
});

Upvotes: 3

Views: 2640

Answers (2)

George Faraj
George Faraj

Reputation: 43

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.

Upvotes: 0

antoniodvr
antoniodvr

Reputation: 1259

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/

Upvotes: 2

Related Questions