gpt4 book ai didi

node.js - 如何发送批量 MongoDB count() 查询?

转载 作者:可可西里 更新时间:2023-11-01 10:01:59 26 4
gpt4 key购买 nike

我的应用程序有一个搜索字段并进行自动完成,我首先获取 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)))

附注这按预期工作并返回我想要的东西——只是想避免这么多查询,并可能在可能的情况下将它们捆绑在一起?

最佳答案

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

关于node.js - 如何发送批量 MongoDB count() 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51314243/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com