简体   繁体   中英

Count documents in several collections simultaneously

I want to count the amount of documents in three separate MongoDB collections simultaneously. 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:

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:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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