Chicky
Chicky

Reputation: 1257

$lookup and populate, which is faster in mongoose?

As you know, mongodb is a document oriented database, so I don't have relationship between 2 objects. With mongoose, it's have a function called populate to JOIN 2 collection with each other, so we have to use populate or $lookup to get data from other collection with a reference field.

But which way is faster ?

Sample:

Users: {
  _id: ObjectId,
  refId: {
    type: ObjectId,
    ref: 'Comments'
  }
}


db.Users.find().populate({ path: 'refId' });

or 

db.User.aggregate([
  {
    $lookup: {
      from: 'Comments',
      localFields: 'refId',
      foreignField: '_id',
      as: 'comments'
    }
  }
])

Upvotes: 2

Views: 2563

Answers (1)

Artem Arkhipov
Artem Arkhipov

Reputation: 7455

Under the hood, the mongoose's populate method doesn't use $lookup meaning that it runs multiple queries to database in order to get populated documents.

Taking this fact, we may assume that using $lookup in aggregate query might be more efficient and fast as it is a part of a single query and is processed by mongo engine on server all together. So, in theory, using $lookup must be faster.

However, it doesn't mean that you should not use populate. Mongoose populate is very useful and powerful and can be used in various cases. In some situations you can achieve much cleaner and readable code using populate rather than writing complicated raw queries. And I believe that usually you will not experience any noticeable performance impact, so it seems to be a good tradeoff.

Upvotes: 5

Related Questions