[英]How to get count in mongodb using aggregation query?
I tried to get the count of Database using an aggregation query.我尝试使用聚合查询获取数据库的计数。
MY Scenrio我的场景
Access使用权
[{
"id": 1,
name: 'laptop'
}, {
"id": 2,
name: 'deasktop'
}]
Query询问
db.access.aggregate([
{
$match: {}
},
{
$group: {
total: { $sum: 1 }
}
}
])
Exceute the query执行查询
I got the output我得到了输出
[{
"total": 2
}]
Excepted output异常输出
{
total: 1
result: [{
"id": 1,
name: 'laptop'
}, {
"id": 2,
name: 'deasktop'
}]
}
How to get this output using aggregation query.如何使用聚合查询获取此输出。
You need to $push
your documents in $group
stage你需要在$group
阶段$push
你的文件
db.access.aggregate([
{
$match: {}
},
{
$group: {
_id: null,
result: {
$push: "$$ROOT"
},
total: {
$sum: 1
}
}
},
{
$project: {
_id: 0
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.