我有一个像这样的视频架构:
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 });
通过这样的模式,我可以对我的视频集合执行任何类型的查找查询并用其评论填充它:
Video.find({ owner: someUserId }).populate({ path: 'comments' });
我的问题是,将评论 ID 保留在视频集中有多大必要?鉴于我已经在评论模式中对 videoId 字段建立了索引,那么去掉这些评论 id 及其计数并使用聚合 $lookup 来查找视频的评论(就性能而言)会有多糟糕,如下所示:
Video.aggregate([
{
$match: {
owner: someUserId,
},
},
{
$lookup: {
from: 'comments',
localField: '_id',
foreignField: 'videoId',
as: 'comments',
}
}
])
它们在性能方面有何不同?