如何从 mongodb 集合的查询中获取计数?

问题描述

我想创建一个过滤器体验,我从请求参数中获取过滤条件,并使用 mongo 聚合框架对数据进行过滤。请建议我一个合适的方法。

让收集的数据像

        {
            "material": "silver","type": "beads","shape": "round","_user": "5f9b78bf1130ca88e2e1d"
        },{
            "material": "mixed","type": "jewels",{
            "material": "gold","shape": "other","_user": "5fda2b717112437f9c06"
        },{
            "material": "silver","_user": "5fda2b717112437f9c706"
        },

让查询的数据为 _user 等于 5f9b78bf1130ca88e2e1d, 材料等于一组银,混合, 类型等于一组珠子、珠宝 & 形状等于 round

的数组

我的查询应返回每个过滤器类别(用户、材料、形状、类型)中的后续计数。

data = {
  categorizedByUser: [
    {
      _id: '5f9b78bf1130ca88e2e1d',count: 2
    },{
      _id: '5fda2b717112437f9c06',count: 0
    },],categorizedByMaterial: [
    {
      _id: 'silver',count: 1
    },{
      _id: 'mixed',{
      _id: 'gold',categorizedByShape: [
    {
      _id: 'round',{
      _id: 'other',]
  categorizedByType: [
    {
      _id: 'beads',{
      _id: 'jewels',]
]

解决方法

您可以使用 $facet 对传入的数据进行分类

db.collection.aggregate([
  {
    $facet: {
      categorizedByUser: [
        {
          $group: {
            _id: "$_user",count: {
              $sum: 1
            }
          }
        }
      ],categorizedByMaterial: [
        {
          $group: {
            _id: "$material",categorizedByShape: [
        {
          $group: {
            _id: "$shape",categorizedByType: [
        {
          $group: {
            _id: "$type",count: {
              $sum: 1
            }
          }
        }
      ]
    }
  }
])

工作Mongo playground

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...