我需要更新/保存大小在100 to 800 to之间的文档。像console.time('save'); await doc.findByIdAndUpdate(...).lean(); console.timeEnd('save');这样的更新操作需要超过5秒-10秒才能完成。更新最多包含~50 at。
正在更新的大型文档属性的结构如下:
{
largeProp: [{
key1: { key1A:val, key1B:val, ... 10 more ... },
key2: { key1A:val, key1B:val, ... 10 more ... },
key3: { key1A:val, key1B:val, ... 10 more ... },
...300 more...
}, ...100 more... ]
}我使用Ubuntu上的Node.js服务器和mongoose.js,MongoDB托管在单独的服务器上。MongoDB服务器没有显示出任何异常的负载,它通常停留在7%的CPU以下,但是我的Node.js服务器将达到100%的CPU使用率,而只是这个更新操作(经过.findById()和一些快速逻辑,8ms-52 8ms)。对于相同的对象,.findById()大约需要500 1s 1。
我需要这些节省更快,我不明白为什么这是如此缓慢。
发布于 2020-07-03 02:57:40
我没有对Mongoose查询做更多的分析。相反,我测试了一个本机MongoDB查询,它大大提高了速度,因此我将继续使用本机MongoDB。
const {ObjectId} = mongoose.Types;
let result = await mongoose.connection.collection('collection1')
.aggregate([
{ $match: { _id: ObjectId(gameId) } },
{ $lookup: {
localField:'field1',
from:'collection2',
foreignField:'_id',
as:'field1'
}
},
{ $unwind: '$field1' },
{ $project: {
_id: 1,
status: 1,
createdAt: 1,
slowArrProperty: { $slice: ["$positions", -1] } },
updatedAt: 1
}
},
{ $unwind: "$slowArrProperty" }
]).toArray();
if (result.length < 1) return {};
return result[0];这个查询,以及对我的数据模型进行一些重构,解决了我的问题。具体来说,文档属性非常大并导致问题,我使用上面的{ $slice: ["$positions", -1] } }一次只返回数组中的一个对象。
从切换到本机MongoDB查询(在猫鼬包装中),我看到了查询速度在60倍到3000倍之间的提高。
https://stackoverflow.com/questions/62587781
复制相似问题