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

时间:2018-07-12 20:50:12

标签: node.js mongodb mongodb-query node-mongodb-native

我的应用程序有一个搜索字段,并且要执行自动填充,首先获取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。这可以按预期工作,并返回我想要的内容-只是想避免那么多查询,并尽可能将它们捆绑在一起?

1 个答案:

答案 0 :(得分:3)

您可以在单个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}}}
])