因此,我想要做的是获得每个省、每个类型提供的体育活动的总数.柏林和科隆的活动项目是 run 和游泳 输出应如下所示:

{ 
    "_id" : {
        "province" : "Berlin", 
        "type" : "Running"
    }, 
    "number" : 2.0
}
{ 
    "_id" : {
        "province" : "Berlin", 
        "type" : "Swimming"
    }, 
    " number" : 2.0
}
{ 
    "_id" : {
        "province" : "Cologne", 
        "type" : "Running"
    }, 
    "number" : 2.0
}
{ 
    "_id" : {
        "province" : "Cologne", 
        "type" : "Swimming"
    }, 
    "number" : 1.0
}

我的查询如下所示,我没有得到我想要的结果.它向我展示了哪些省份的 run 和游泳是不是柏林或科隆的活动.我试着输入$或插入$,但仍然没有产生我想要的结果.我遗漏了什么?

db.getCollection("Sport").aggregate([
    {$match: {$or: [{province: "Cologne"}, {province: "Berlin"}], $or: [{type: "Running"}, {type: "Swimming"}]}},
    {$group: {_id: {province: "$province", type: "$type"}, count: {$sum: 1}}},
    {$sort: {count: -1}}
])

推荐答案

Tom SLabbaert已经有了很好的输入,但不知道您的数据 struct 实际是什么样子,很难指出错误所在.但是,如果字段"type"或"省级"是数组,则需要首先展开该字段.

  {
    $unwind: "$type"
  },
  {
    $match: {
      $and: [
        {
          $or: [
            {
              province: "Berlin"
            },
            {
              province: "Cologne"
            }
          ]
        },
        {
          $or: [
            {
              type: "Running"
            },
            {
              type: "Swimming"
            }
          ]
        }
      ]
    }
  }

Mongodb相关问答推荐

MongoDB通过查找具有多个数组的对象进行聚合

字段$set聚合导致错误美元($)前缀字段$concatArrays对于存储无效"

MongoDB DB参考返回null值

MongoDB查询优化

我可以在 MongoDB 中将字段值设置为对象键吗?

Mongoose 和 MongoDB,如何在具有多个引用的两个模型之间创建关系?

MongoDB:使用数组过滤器进行更新插入

如何在mongoDB中按嵌套文档分组( group by )

从嵌套数组中 id 匹配的另一个集合中获取所有字段

使用 mgo 从 golang 中的 Mongodb 中 Select 列

查找对象是否在预保存钩子mongoose中更改

具有最佳插入/秒性能的数据库?

如何在 MongoDb 中使用杰克逊将日期字段存储为 ISODate()

在mongodb中实现分页

为什么不建议在 MongoDB 中使用服务器端存储函数?

适用于 Windows 10 64 位的 MongoDB 下载

Java + MongoDB:更新文档中的多个字段

MongoDB 用 $type 匹配一个数组?

'this' 在 Mongoose 预保存挂钩中未定义

在 MongoDB 中比较日期(moment.js)