Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB $lookup vs Mongoose populate

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?

like image 896
YulePale Avatar asked Jun 24 '20 14:06

YulePale


People also ask

What is Mongoose populate?

populate() function in mongoose is used for populating the data inside the reference. In your example StorySchema is having _creator field which will reference to the _id field which is basically the ObjectId of the mongodb document. populate() function can accept a string or an object as an input.

What does populate method do mongoose?

Mongoose Populate() Method. 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.

Can we use populate in aggregate?

Short answer: You can't.


Video Answer


1 Answers

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.

like image 66
YulePale Avatar answered Nov 14 '22 19:11

YulePale