如何在 MongoDB 中正确使用 $group 运算符?

雅各布普鲁塔

我目前正在努力使用 MongoDB 查询,我想在其中按 2 个字段myId对数据进行分组myType,但我得到的结果看起来不像我需要的。我的目标是对每个myId结果进行myType分组。喜欢:

myId : {myType1 : 5, myType2 : 3, myType3 : 1}

但是,当我尝试使用组运算符提供查询时,如下所示:

db.collection.aggregate([{
"$project": {
  "myId": "$myId",
  "myType": "$eventType",
  }
},
{
   "$group":{
      "_id":{
         "myId":"$myId",
         "myType":"$Type"
      },
      "count":{
         "$sum":1
      }
   }
}
])

这种分组返回的结果如下所示

[{'_id': {'myId': 'qwerty123', 'myType': 'created', 'count': 1}}, 
{'_id': {'myId': qwerty123', 'myType': 'removed', 'count': 3}},
{'_id': {'myId': qwerty123', 'myType': 'updated', 'count': 2}},
{'_id': {'myId': 'asd123', 'myType': 'created', 'count': 1}}, 
{'_id': {'myId': asd123', 'myType': 'removed', 'count': 2}}]

但我想实现的是如下结构:

[{'_id': {'myId': 'qwerty123', 'myType': {'created' 1, 'removed' : 3, 'updated' : 2}}},
{'_id': {'myId': 'asd123', 'myType': {'created' 1, 'removed' : 2}}}]

或者像这样:

[{'qwerty123', 'myType': {'created' 1, 'removed' : 3, 'updated' : 2}},
{'asd123', 'myType': {'created' 1, 'removed' : 2}}]

是否可以$group通过上述模式获得操作员的结果如果是,我该如何实现?

谢谢你。

阿什

在你上面一个之后使用下面的阶段

db.collection.aggregate([
  { $group: {
        _id: "$_id.myId",
        myType: {
            $push: {
                $arrayToObject: [
                    [
                        {
                            k: "$_id.myType",
                            v: "$_id.count"
                        }
                    ]
                ]
            } 
        }
    }}
])

蒙戈游乐场

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Golang中正确使用OR运算符

如何在MongoDB中使用“不喜欢”运算符

如何在Strongloop中使用MongoDB运算符

如何从rxjs包中正确导入运算符

如何在React JS中正确使用三元运算符?

如何在mongodb中使用$ or运算符查找两个条件

如何在mongodb的typeorm中使用“ OR”运算符

如何在flink运算符中正确处理异常?

如何正确使用减号运算符?

在mongoDB中收到未知的组运算符'$ group'的错误

如何在聚合管道mongodb中使用$ update / $ set运算符?

如何在mongodb中使用$ nin运算符从集合中获取文档

MongoDB:如何在不使用$ group运算符的情况下计算总数

如何在mysql中正确使用exists运算符?

如何在mongodb中使用$ and运算符-Java驱动程序

如何在使用$ push运算符时确保mongodb数组中的项是唯一的

在mongodb中使用Like运算符

何时在mongodb中使用“ $ and”运算符?

如何对MongoDB聚合管道使用多个运算符?

MongoDB:使用$ geoWithin运算符无法获得正确的结果

如何在Strongloop环回中使用mongoDB的提示运算符?

如何在Spring Data MongoDB中使用$ arrayElemAt运算符

如何在Swift中正确使用conditionak运算符

如何在 Loopback 4 中使用 MongoDB 扩展运算符?

如何在 kotlin 中正确重载运算符

如何在 mongodb $group 运算符中获取数组的长度?

如何在 Python 中正确使用“not()”运算符

如何在 Javascript/Typescript 中正确使用扩展运算符

在 mongodb 中使用 $or 运算符的条件