Reputation: 8678
The problem is simple:
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:
locked
the oldest session with status: { $nin: ['locked', 'success']}
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
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