简体   繁体   English

同时统计几个collections中的文档

[英]Count documents in several collections simultaneously

I want to count the amount of documents in three separate MongoDB collections simultaneously.我想同时计算三个单独的 MongoDB collections 中的文件数量。 What I have right now works but is slow.我现在拥有的东西有效但速度很慢。 Can anyone please help me to optimize it?谁能帮我优化一下?

app.post('/fetch-numbers',(req, res) => {
  let numbers = {};
  Clinic.countDocuments({})
  .then(clinicCount => {
    numbers.clinicCount = clinicCount;
    Dentist.countDocuments({})
    .then(dentistCount => {
      numbers.dentistCount = dentistCount;
      Booking.countDocuments({})
      .then(bookingCount => {
        numbers.bookingCount = bookingCount;
        res.json(numbers)
      })
    })
  })
  .catch(err => {
    res.json(err)
  });
});

Since all your queries are independent, you can run them all in parallel with promise.all() , code will look like:由于您所有的查询都是独立的,因此您可以使用promise.all()并行运行它们,代码如下所示:

app.post('/fetch-numbers', async (req, res) => {
    Promise.all([
        Clinic.countDocuments({}),
        Dentist.countDocuments({}),
        Booking.countDocuments({})
    ])
    .then((docCounts) => {
        const numbers = docCounts.reduce((a, b) => a + b, 0)
        res.json(numbers);
    })
    .catch(err => res.json(err));
    const numbers = docCounts.reduce((a, b) => a + b, 0)
    res.json(numbers);
});

You can further make it more readable by using async-await with Promise.all() , eg:您可以通过将async-awaitPromise.all()一起使用来进一步使其更具可读性,例如:

app.post('/fetch-numbers', async (req, res) => {
    try {
        const docCounts = await Promise.all([
            Clinic.countDocuments({}),
            Dentist.countDocuments({}),
            Booking.countDocuments({})
        ]);
        const numbers = docCounts.reduce((a, b) => a + b, 0)
        res.json(numbers);
    } catch(err) {
        res.json(err);
    }
});

You can read more here Promise.all() , async-await and async-await with Promise.all()你可以在这里阅读更多Promise.all() , async-awaitasync-await with Promise.all()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM