MongoDB九大优化方式:
第一:单次批量查询比循环逐条查询更快;
循环查询是开发者最常犯的错误写法。循环嵌套查询写代码快,逻辑简单,最耗时。在小批量数据处理时间一般远小于数据库查询时间。所以尽量避免增加查询次数,能把多次查询合并成单次批量查询尽量查询。解决办法:先预处理把查询字段合并成一个数组,然后数组中的同类项,接着用批量查询(包括管道操作),转成map,最后用map的get方法查找数据。
let list = await VRRecord.find({
type: '航拍',
status: {
$in: ['', null, 'FINISH']
}
}, '-_id -estate_id -views_num').sort({
create_time: -1
}).lean().exec();
// let time1 = new Date().getTime();
// logger.debug('time1-time0:', time1-time0, 'list.length:', list.length);
// 使用map和concat来遍历list,并提取每个元素的estates数组
let newList = [].concat(...list.map(item => {
// 确保estates是一个数组
return Array.isArray(item.estates) ? item.estates : [];
}));
// 使用Set来去除重复的
newList = Array.from(new Set(newList));
// logger.debug('newList:', newList);
let subUserMap = new Map();
if