1

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'
    }
  }
])
Vũ Anh Dũng
  • 980
  • 3
  • 13
  • 32
  • Does this answer your question? [MongoDB $lookup vs Mongoose populate](https://stackoverflow.com/questions/62557902/mongodb-lookup-vs-mongoose-populate) – nimrod serok May 06 '22 at 14:42

1 Answers1

4

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.

Artem Arkhipov
  • 7,025
  • 5
  • 30
  • 52
  • Yes thank you for more details. As my understand, with a simple query we can use populate, it's lighter, cleaner. With a complex business and must be fast, we'll need a aggregate. – Vũ Anh Dũng Aug 03 '21 at 08:25