Implement “Joins” in MongoDB equivalent to SQL

Since I am coming from a SQL background so writing queries in SQL where I join tables is quite simple but I guess I am missing that in Mongoose / Mongodb. In earlier version of MongoDB we can’t perform “joins” equivalent to SQL.

As of MongoDB 3.2 above statement is no longer correct. The new $lookup operator added to the aggregation pipeline is essentially identical to a left outer join. Continue reading


MongoDB Pagination using skip() and limit()

How to implement pagination with MongoDB??

Let’s for example I have collection named ‘persons’ and add some documents on it.

db.persons.insert({fname:'John', lname: 'Paton'});
db.persons.insert({fname:'Bob', lname: 'Warner'});
db.persons.insert({fname:'Pankaj', lname: 'Gupta'});
db.persons.insert({fname:'Atul', lname: 'Mishra'});

The traditional approach to pagination requires use of  skip() and limit() MongoDB cursor functions. Let’s have a look how we can use these cursor functions to achieve pagination.

db.persons.find().skip(ITEMS_PER_PAGE * (PAGE_NUMBER - 1)).limit(ITEMS_PER_PAGE);

ITEMS_PER_PAGE” – Represents number of items per page.

PAGE_NUMBER” – Represents current page number.

Use db.persons.count() to get the number of documents in the collection and implement the pagination navigation links.

This pagination technique works as you expect and is excellent in every way – as long as you have a small set of data. If you have a collection with hundreds of thousands of documents, this method of pagination will fail – it will become slower with every increasing page. That’s because the cursor has to start from the beginning of the collection to the skip position for every request, and with increasing page number the skip position becomes farther and farther.