【发布时间】:2019-10-25 14:51:23
【问题描述】:
我有一个像这样的视频架构:
const VideoSchema = new mongoose.Schema({
caption: {
type: String,
trim: true,
maxlength: 512,
required: true,
},
owner: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true,
},
// some more fields
comments: [{
type: mongoose.Schema.ObjectId,
ref: 'Comment',
}],
commentsCount: {
type: Number,
required: true,
default: 0,
},
}, { timestamps: true });
还有一个像这样的简单评论模式:
const CommentSchema = new mongoose.Schema({
text: {
type: String,
required: true,
maxLength: 512,
},
owner: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true,
},
videoId: {
type: mongoose.Schema.ObjectId,
ref: 'Video',
required: true,
index: true,
},
}, { timestamps: true });
通过这样的架构,我可以对我的视频集合执行任何类型的查找查询并使用其 cmets 填充它:
Video.find({ owner: someUserId }).populate({ path: 'comments' });
我的问题是在视频集合中保留评论 ID 有多大必要?鉴于我已经在我的 Comment 模式中索引了 videoId 字段,摆脱这些评论 id 和它们的数量并使用聚合 $lookup 来查找视频的 cmets 会有多糟糕(谈到性能):
Video.aggregate([
{
$match: {
owner: someUserId,
},
},
{
$lookup: {
from: 'comments',
localField: '_id',
foreignField: 'videoId',
as: 'comments',
}
}
])
这些在性能方面有何不同?
【问题讨论】:
标签: node.js mongodb mongoose aggregation-framework