如何发送批量 MongoDB count() 查询?

How to send bulk MongoDB count() queries?

我的应用程序有一个搜索字段并执行自动完成,我首先获取 distinct() 值,然后立即为每个不同的值发送一个 count() 查询。可以有几十个值然后计算,这是很多查询。

知道如何使用 MongoDB 的 NodeJS 模块避免大量查询吗?

现在,查询是这样的:

const baseQuery = {
    "organization": organization,
    "status": "processed"
}

let domains = []

// A. Query to get the disinct values
MongoDB.getMainCollection().distinct(`location.hostname`, { organization, status: "processed" })

    // B. Got the value, now creating a COUNT() query for each
    .then(list => {
        domains = list.map((host,idx) => Object.assign({}, { domain: host, count: 0, idx: idx }))
        const countingPromises = list.map(host => MongoDB.getMainCollection().count(Object.assign({}, baseQuery, { "location.hostname": host })))
        return Promise.all(countingPromises)
    })

    // C. Putting it all together
    .then(values => {

        values.forEach((count, idx) => {
            const domain = domains.find(d => d.idx === idx)
            if (domain) {
                domain.count = count
            }
        })

        domains.sort((a,b) => b.count - a.count)

        resolve(domains)
    })

    .catch(err => reject(new AppError(`Error listing hostnames for @${organization}.`, 500, err, payload)))

p.s。这按预期工作 returns 我想要的 - 只是想避免这么多查询,如果可能的话可能将它们捆绑在一起?

您可以在单个 aggregate 查询中获取所有不同的值及其计数:

MongoDB.getMainCollection().aggregate([
    // Filter for the desired docs
    {$match: baseQuery},
    // Group the docs by location.hostname and get a count for each
    {$group: {_id: '$location.hostname', count: {$sum: 1}}}
])