分页的Mongodb聚合查找工作缓慢

时间:2019-11-25 13:33:36

标签: mongodb pagination mongodb-query aggregation-framework

我在nodejs和mongodb中是一个非常新的人,下面的查询只需要20秒左右的时间即可读取10条记录。如何优化下面的查询以快速获取数据?预先感谢

const skip = pageSize * (pageNo - 1);
const limit = pageSize;

const stages = [
  { $sort : { id : -1 } },
  { $match : { is_active : { $eq : 1 } } },
  { $lookup:{ from: 'offences', localField:'offences', foreignField: 'offence_id', as: 'offenceSetail' } },
  { $project: { 'offences.is_active' : 0, } },
  { $replaceRoot : { newRoot : { $mergeObjects : [ { $arrayElemAt: [ "$offenceSetail", 0] }, "$$ROOT"] } } },
  { $project: { 'offenceSetail' : 0 } },
  { $lookup: { from: 'registers', localField: 'user_id', foreignField: 'id', as: 'sender'} },
  { $project: { 'registers.is_active' : 0 } },
  { $replaceRoot : { newRoot : { $mergeObjects : [ { $arrayElemAt: ['$sender', 0] }, "$$ROOT"] } } },
  { $project: { 'sender': 0 } },
  { $facet : { length : [ { $count : "total" }], data : [ { $skip: skip }, {$limit: limit } ] } },
];

Complaint.aggregate(stages)
  .allowDiskUse(true)
  .then(result => {
    return res.status(200).json({
      result: result[0]["data"],
      length: result[0]["length"][0]["total"]
    });
  });

样本o / p:

length : [{total: 6}],
data: [
{id: 1,create_at: 26-11-2019 12:00, offence: Driving Dangerously, name: Vicky},
{id: 2,create_at: 26-11-2019 12:00, offence: Without Helmet, name: Vikash},
{id: 3 ,create_at: 26-11-2019 12:00, offence: Parking illegal, name: Vishesh},
{id: 4,create_at: 26-11-2019 12:00, offence: Driving Dangerously, name: Shakti},
{id: 5 ,create_at: 26-11-2019 12:00, offence: Without Helmet, name: Rajat},
{id: 6 ,create_at: 26-11-2019 12:00, offence: Parking illegal, name: Nadeem}
]
}

0 个答案:

没有答案