17

I have seen this and other similar titled questions, none answer my question.

I was going through the mongoose documentation where I read

MongoDB has the join-like $lookup aggregation operator in versions >= 3.2. Mongoose has a more powerful alternative called populate(), which lets you reference documents in other collections.

How does populate() in mongoose work that makes it more powerful than MongoDB's $lookup?

Isn't mongoose a tool that helps nodejs users work with mongodb. If so how can mongoose have functionalities that MongoDB does not? Like populate()?

Does mongoose's populate() method use MongoDB's $lookup behind the scenes?

YulePale
  • 6,688
  • 16
  • 46
  • 95
  • 1
    https://github.com/Automattic/mongoose/issues/3683#issuecomment-334025713 – Orelsanpls Jun 24 '20 at 15:01
  • 2
    Thanks for the link. I have read the whole thread. Now I know that mongoose's `populate()` method does not use MongoDB's `$lookup` behind the scenes. And I have understood that the populate method does several trips to the DB to populate. I have also seen that in getting an array of docs `populate()` is faster. But why do people want `populate()` to use `$lookup`? – YulePale Jun 24 '20 at 15:19
  • 1
    Make populate to use $lookup under the hood would allow people to use `.populate()` syntax over `$aggregation`. If you needs `$lookup` performance, then you must use `$aggregation` at this moment. Also it would be better if mongoose use what's available in mongodb instead of doing it's own "framework" function. – Orelsanpls Jun 24 '20 at 15:31
  • 1
    @GrégoryNEUT I have asked [another similar question](https://stackoverflow.com/questions/62559332/mongodb-aggregation-vs-mongoose-virtuals) on the same topic. Kindly have a look. Thanks. – YulePale Jun 24 '20 at 16:05

1 Answers1

15

Thanks to a github thread shared by Grégory NEUT in the question's comments I have been able to establish certain facts:

  1. Mongoose's populate() method does not use MongoDB's $lookup behind the scenes. It simply makes another query to the database.
  2. Mongoose does not have functionalities that MongoDB does not have. populate() just makes two or more queries.

How does populate() in mongoose work that makes it more powerful than MongoDB's $lookup?

In my opinion, there are places to use populate() and others to use $lookup. For more complex queries $lookup in an aggregation pipeline would work best.

YulePale
  • 6,688
  • 16
  • 46
  • 95