rileyjshaw
rileyjshaw

Reputation: 23

Efficiently access most recently accessed MongoDB entries?

I'm making a service with similar requirements to a URL shortener; I need to store a bunch of unique hashes and their corresponding strings. The tricky part is that I also need to order them by access date so that I can retrieve the last 10 accessed entries (and the next 10 after that, etc.)

Everything that I've come up with so far is grossly inefficient. What's the best way to store a queue like this?

Upvotes: 0

Views: 37

Answers (1)

Chris Heald
Chris Heald

Reputation: 62688

One solution: Add an accessed_at field which you update when the url is accessed. Index it, then you can find URLs sorted by the accessed_at field.

You could alternately use a capped collection that holds recently accessed URLs; each time a URL is accessed, insert it into the capped collection. That will give you a rolling window of the most recent accesses. It won't deduplicate, though, so if a URL is particularly popular, it will show up in that list multiple times.

Upvotes: 2

Related Questions