Search code examples
node.jsmongodbmongoose

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?


Solution

  • Here's a summary of the differences:

    $lookup

    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