MongoDB findOne和Update写入冲突会显著影响性能



我在使用MongoDB时遇到了性能问题。

我们的数据库在imagehashtag之间有松散的连接。当服务器保存新图像时,它将从hashtag更新imageCount值。问题是同一主题标签上可以同时有数百个更新。由于写入冲突,保存速度非常慢。

我是否误解了应该如何建立这种联系?是否有可能使这项工作更快?

谢谢!

当前方法更新主题标签查询:

const dbHashtag = await Hastag.findOneAndUpdate(
{ name: hashtag.name },
{ $inc: { videoCount: 1 } },
{ upsert: true, new: true }
).select('_id').lean()

图像架构:

const imageSchema = new mongoose.Schema({
hashtags: [{ type: Schema.Types.ObjectId, ref: 'Hashtags' }]
})

标签架构:

const hashtagSchema = new mongoose.Schema({
name: {
type: 'String',
unique: true
},
imageCount: {
type: 'Number'
},
})
hashtagSchema.index({ name: 1 })

这是我的错误。早些时候,我在图像和主题标签之间有很多关系。

const hashtagSchema = new mongoose.Schema({
name: {
type: 'String',
unique: true
},
imageCount: {
type: 'Number'
},
images: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Image"
}
]
})

我从标签中删除了图像列表,因为它可能超过 100000 个 ID。问题是我刚刚从模型中删除了行,但数据仍在数据库中。从数据库中删除视频列表可以解决此问题。

await Hastag.updateMany({}, { $unset: { images: 1 } })

最新更新