So, I need to get the latest notifications, and I’ve been considering to store them like this:
{
"_id" : "...",
"userId" : "...",
"date" : 1564333565,
"type" : "FOLLOW",
"notifierId" : "...",
"index" : 4
}
With ‘index’ being just a counter.
Then I would do:
Notifications.rawCollection().createIndex({ index: 1 });
(I’m not indexing by ‘date’ because they can overlap)
The problem is that if I try to get the latest two, I get indexes 0 and 1.
db.getCollection(‘Notifications’).find({‘index’:{$lt:4}}).limit(2).explain()
That uses IXSCAN, which is good. But if I try to count from the last like this:
db.getCollection(‘Notifications’).find({‘index’:{$lt:4}}).limit(2).sort( { $natural:-1 } ).explain()
I get the correct results, but it uses a COLLSCAN.
So I thought, “instead of creating indexes and doing tricky commands, why don’t I just create blocks with ids?”
Example of NotificationBlocks:
{
"_id" : "...",
"userId" : "...",
// holds 30 ids max
"notificationIds":['rosJydD9woxo9tT7P', 'DuLQZBFmKwdfzdXGJ', 'ztjXH6TNYqGvQgh3G', ...],
"prevBlock":'D43TZ3ih2h8PDDGFr',
"nextBlock":'CNrAyc87yAzoHPps3'
}
That way, I just check the user profile to get the id of the latest block, then I can get the ids of the latest 30 notifications. If I need more, I check if there’s a previous block.