猫鼬填充与聚合 [英] Mongoose populate vs aggregate

查看:59
本文介绍了猫鼬填充与聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 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 版本要求

这篇关于猫鼬填充与聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆