猫鼬填充与聚合

猫鼬填充与聚合

问题描述:

我注意到 mongoose 4.7.3 中的 .populate 函数为每次查找在数据库上运行单独的查询:

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',
      },

mongoose 用 .populate 做单独查询的原因是什么?聚合函数在查找上的性能是否更高?

What is the reason for mongoose to do separate queries with .populate? Is the aggregation function more performant on lookups?

以下是差异的摘要:

$lookup

  • 只能与aggregate
  • 一起使用
  • 只能用于从 未分片的集合
  • 可以按任何字段拉入引用文档
  • 通常性能更高,因为它是服务器端操作
  • 需要 MongoDB 3.2+

猫鼬 populate()

  • 可以与 findaggregate
  • 一起使用
  • 可用于从分片和非分片集合中提取引用文档
  • 只能通过_id
  • 拉入引用的文档
  • 无 MongoDB 版本要求