dkx22
dkx22

Reputation: 1133

Delete record on timer + one condition

My program is an online game. I create a game object which contains players. I want to remove the game record after 3 hours if no other player (than the one who created the game) joined the game. I can count players, and I know about mongodb TTL but how can I set a TTL that will only trigger is there is no multiple players?

Upvotes: 1

Views: 119

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50416

The basics of using a TTL index is that the document will be deleted after the specified seconds has passed from the time recorded in the index field. What may not be clearly apparent is that though the documentation examples use a field called "createdAt", this does not mean this is your only restriction, as the date field can be updated.

So for instance if you create a document and give it an "updatedAt" field, that you populate when the game is created, then provide the index definition:

db.games.createIndex({ "updatedAt": 1 },{ "expireAfterSeconds": 10800 })

Then all you really have to do is "update" that value whenever a new player joins the game, or there is some other action that keeps the game "valid":

db.games.update(
   { "_id": gameId },
   {
       "$push": { "players": newPlayer },
       "$currentDate": { "updatedAt": true }
   }
)

Or change score:

db.games.update(
   { "_id": gameId },
   {
       "$inc": { "score": 20 },
       "$currentDate": { "updatedAt": true }
   }
)

Also using the $currentDate operator if you choose.

So the "expire date" for a TTL index is not "set", it just works on a process that checks the "current time" and removes any data where the indexed field of a TTL index is older than the current time "minus" the expiry seconds set on the index.

In short, create the index and just keep updating the field to keep the document current. As things change, players join or leave update the field.

Upvotes: 1

Related Questions