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?
Short answer: You can't. Long answer: In the Aggregation Framework, the returned fields are built by you, and you're able to "rename" document properties.
In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.
Mongoose's aggregate() function returns an instance of Mongoose's Aggregate class. Aggregate instances are thenable, so you can use them with await and promise chaining. The Aggregate class also supports a chaining interface for building aggregation pipelines.
Now while lookup is twice as fast with findOne than populate is the difference in the grand scheme of things is marginal (0.5ms vs 1.5ms).
Here's a summary of the differences:
$lookup
aggregate
Mongoose populate()
find
and aggregate
_id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With