Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose populate vs aggregate

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?

like image 504
F.H. Avatar asked Apr 08 '19 14:04

F.H.


People also ask

Can I use populate with aggregate?

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.

What does populate in Mongoose mean?

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.

What does aggregate do in mongoose?

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.

Is populate faster than Lookup?

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).


1 Answers

Here's a summary of the differences:

$lookup

  • can only be used with aggregate
  • can only be used to pull in referenced documents from unsharded collections
  • can pull in referenced documents by any field
  • generally more performant as it's a server-side operation
  • requires MongoDB 3.2+

Mongoose populate()

  • can be used with find and aggregate
  • can be used to to pull in referenced documents from both sharded and unsharded collections
  • can only pull in referenced documents by _id
  • no MongoDB version requirement
like image 84
JohnnyHK Avatar answered Oct 15 '22 09:10

JohnnyHK