Reputation: 19581
I'm looking for a solution to the following :
I have a sortable, paginated table representing collection in mongodb
To take the initial results and each page I use the following
var defaultRows = 10;
var defaultPage = 1;
var defaultSort = ['name'];
var page = defaultPage - 1;
var totalPages = Math.ceil(db.table.count() / defaultRows);
var results = db.table.find().skip(page * defaultRows).limit(defaultRows).sort(defaultSort);
So I'm searching for a solution of a search for document and returning the exact page of this document according to the sort variable.
I've came up with this, but it would not scale very well on large collections.
var counter = 0;
var page = 1;
var queryName = 'smth';
db.table.find().sort(defaultSort).forEach( function ( doc ) {
if ( doc.name === query.Name ) return false;
counter++;
if ( counter === 10 ) { counter = 0; page++ };
});
print page; // Here page will give me the correct page
But If I have a large table wouldn't it be wrong to parse it all through forEach and load it as collection? Is there any easier way to do that, which is more scalable.
*Of course this is raw mongo javascript console script, I'm using mongoosedb as node.js driver, but it looks very similar to this!
Upvotes: 2
Views: 1301
Reputation: 54
I know your usecase. You want to display a paginated list with a preselected item in the list. Aka, the correct page has to be found to load from mongo.
I used a different approach using something like this:
db.user.find({name: {$lt: "foo"}}).sort({name: 1}).count()
This will retrieve the poistion of the selected item using your selected sort.
Now you can calulate the correct page as before.
Upvotes: 3
Reputation: 4228
You should keep track of any changes by using the unique document id. You should not use position in the result set as the identifier of the document.
Upvotes: 0