node.js - Nodejs和express js中的mongodb聚合
问题描述
下面的聚合在 mongo db 中工作,但是当我尝试将它与节点 js 集成以获取计数值时API
,它返回 null 值
我目前正在寻找Aggregation
在Node js
.
下面是与node js的集成代码
app.get('/count', (req, res) => {
var name = req.params.name;
adpostdata.aggregate([
{ "$facet": {
"Total": [
{ "$match" : { "category": { "$exists": true }}},
{ "$count": "Total" },
]
}},
{ "$project": {
"Total": { "$arrayElemAt": ["$Total.Total", 0] },
}}
], (err, result) => {
if (err) return console.log(err)
console.log(result)
res.send(result+"")
})
})
我的输入是
{
category :"dress"
}
{
category:"cars"
}
解决方案
谢谢大家的帮助,现在我可以得到我的例外输出了
app.get('/count', (req, res) => {
adpostdata.aggregate(
[
// Count the number of books published in a given year
{
$facet: {
"categories": [
{
$group: {
_id: '$category',
count: { $sum: 1 }
}
},
// Sort by year descending
{ $sort: { count: -1, _id: -1 } }
],
"Total": [
{ "$match" : { "category": { "$exists": true }}},
{ "$count": "Total" },
],
}}]).toArray( (err, result) => {
if (err) return console.log(err)
console.log(result)
res.send(result)
})
})
推荐阅读
- visual-c++ - 结构和枚举类的循环引用问题
- sql-server - 如何在带有后端数据(springboot和mssql)的角度中使用折线图(highcharts)
- javascript - 有没有办法强制显示浏览器的默认“离开站点”确认对话框?
- flutter - 如何从飞镖执行 Add 2 home?
- named-entity-recognition - “合并财务数据”和“表格 8-K”以及类似的法律术语是否算作命名实体(用于命名实体识别)?
- xml - 使用 xslt for-loop 选择 xml 内部数据的值?
- r - 在六边形图上添加黄土回归线
- python - python 根据上个月的最后一个值计算 pct_change()
- shell - 忽略使用 at 命令运行的重复作业
- asp.net-core - 在影子属性上创建索引