【问题标题】:MongoDB populate performanceMongoDB 填充性能
【发布时间】:2018-10-24 05:39:26
【问题描述】:

最近问了这样一个问题。

Mongo 中哪个更快:填充或单独的异步请求?

例子

var mongoose = require('mongoose')
    , Schema = mongoose.Schema;

var FeedPostCommentSchema = new Schema({

    feedPost: {type: Schema.Types.ObjectId, ref: 'FeedPost', index: true},
    user: {type: Schema.Types.ObjectId, ref: 'User'},

    comment: {
        type: String,
        trim: true
    },

    updated: {type: Date, default: Date.now},
    created: {type: Date, default: Date.now, index: true}
});

mongoose.model('FeedPostComment', FeedPostCommentSchema);

在显示所有cmets时,我们还需要获取用户数据

我们可以让它成为标准的填充方法:

FeedPostComment.find({feedPost: req.params.postId}).populate('user')
        .skip(skip)
        .limit(limit)
        .sort({created: -1})
        .lean()
        .exec()

我们也可以通过并行查询来做到这一点:

FeedPostComment.find({feedPost: req.params.postId})
        .skip(skip)
        .limit(limit)
        .sort({created: -1})
        .lean()
        .exec(function (err, comments) {
            async.each(comments, function (comment, cb) {
                User.findById(comment.user, function (err, composer) {
                    if (err) {
                        return cb(err);
                    }

                    comment.user = utils.getPublicDataOfUser(composer);
                    cb();
                });
            }, function (err) {
                comments.reverse();
            });
        });

【问题讨论】:

    标签: node.js mongodb performance async.js mongoose-populate


    【解决方案1】:

    填充通常更快(并且更高效),因为它使用单个 $in 查询来获取所有引用的文档,而不是一个一个地获取它们。

    【讨论】:

      【解决方案2】:

      Populate 总是比正常的异步请求更快...但是现在有比引入的速度更快的方法,即$lookuppipeline...您可能应该使用它。

      【讨论】:

      • $lookup 不能与分片一起使用,所以它会限制水平缩放?
      猜你喜欢
      • 2018-03-28
      • 2021-01-25
      • 2019-06-25
      • 1970-01-01
      • 2017-06-10
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多