I've noticed that .populate function in mongoose 4.7.3 runs separate queries on the database for each lookup:
db.House
.populate('ownerId')
.exec((err, result) => {
..
With aggregation pipeline we can lookup multiple collections with a single query:
db.House.aggregate([
{
$lookup:
{
from: 'owners',
localField: 'ownerId',
foreignField: '_id',
as: 'owner',
},
What is the reason for mongoose to do separate queries with .populate? Is the aggregation function more performant on lookups?
Here's a summary of the differences:
$lookup
aggregate
$lookup
can be used with sharded collections as well).Mongoose populate()
find
and aggregate
_id