Reputation: 1547
Using MongoDB I have a collection of messages.
I've been using .skip()
and .limit()
to retrieve the messages that belong on the current page.
For example:
var pageSize = 20;
var pageNumber = 1;
db.messages.find({}).sort({ created_date: -1 }).skip(pageSize*(pageNumber-1)).limit(pageSize, callback);
My question is, if I have the id of a specific message, what is the best approach to retrieve it's "page" of results?
Upvotes: 1
Views: 969
Reputation: 631
A solution could be retrieve the "created_date" of your doc by _id, then counting how many documents exists before him and dividing the number by your page size.
Example on the shell; if 'XXX' is the given Id then "page" would become the page of your record:
var pageSize = 20
vat tgId = 'XXX'
var when = db.messages.findOne({_id: tgId}, {created_date: 1})['created_date']
var page = Math.ceil(db.messages.find({created_date: {$lt: when}}).count() / pageSize)
Upvotes: 3