mongodb - 获取一个键/值对象,其中键是一个值的枚举
问题描述
在 MongoDB 中,如何获取键/值对象,其中每个键是枚举的值,值是具有枚举值的文档数。
总之,
从
db={
"orders": [
{ "_id": 1, "type": "news" },
{ "_id": 2, "type": "news" },
{ "_id": 3, "type": "news" },
{ "_id": 4, "type": "alert" },
{ "_id": 5, "type": "alert" }
]
}
我怎样才能得到这个:
{
news: 3,
alert: 2
}
我正在使用带有组的聚合,如下所示:
db.orders.aggregate([
{
"$group": {
"_id": "$type",
"count": { "$sum": 1 }
}
}
]);
我明白了:
[
{ "_id": 'alert', "count": 2 },
{ "_id": 'news', "count": 3 }
]
但是从那里开始,我不知道如何转换文档以获得上述预期结果。
Ty 提前!
解决方案
像这样的聚合将起作用:
db.orders.aggregate([
{
"$group": {
"_id": "$type",
"count": { "$sum": 1 }
}
},
{
"$group" : {
"_id": null,
"array": {
"$push": { "k": "$_id", "v": "$count"}
}
}
},
{
"$replaceRoot": {
"newRoot": { "$arrayToObject": "$array"}
}
}
])
第二$group
阶段包含表单对象的数组{ k: type, v: count }
。这是为了让操作员$arrayToObject可以使用它。
然后$replaceRoot阶段用于$arrayToObject
以所需格式输出结果。
推荐阅读
- flutter - 在导航中使用带有 GlobalKeys 的小部件
- html - 春季启动 java.lang.NullPointerException: null
- php - 保存发送的firebase推送通知的正确方法是什么
- react-native - 无法连接到节点 infura
- ios - iOS:Firebase removeValue 似乎正在破坏数组数据?
- python - 预期的二维数组,改为标量数组
- postgresql - 如何正确扫描 pq 数组?
- c++ - 错误:程序停止执行 | 退出代码:255
- c++ - boost文件夹中可用的库文件不匹配
- java - 如何从一个标签中获取多个值