TOPKAT
TOPKAT

Reputation: 8678

How to update the oldest entry (with a sorting function if possible) corresponding to a filter in mongoDb in one update?

The problem

The problem is simple:

Real life use case

I have an session collection that needs to be processed by multiple instances of my app. When ready, an instance lock the oldest session (oldest timestamp if possible, not oldest entry) then process it. This will allow sessions to be "dequeued" in the good order by multiple instances of the app while a unique session is treated only by one instance.

The main query is:

What is the best way to achieve the above query in one update, if possible without using transactions ?


Actually I am firstly retrieving it and updating it in a second time. Please let me know if you need further details.

Upvotes: 0

Views: 43

Answers (1)

João
João

Reputation: 101

You model probably have the timestamps option activated, right? If yes, you should have the createdAt and updatedAt attributes in your documents.

You can get the oldest document in this way:

var documents = await Model
    .find()
    .sort({createdAt: 1})
    .limit(1);
    
var oldestDoc = documents[0];

await Model.findByIdAndUpdate(oldestDoc._id, {
    // data to be updated here =)
})

Upvotes: 1

Related Questions