mongo中如何根据某个字段的多个值来对另一个字段进行统计?

数据库中

{ "_id" : ObjectId("5a66ef690fe318d00bbaf106"), "sex" : "man", "name" : "a" }
{ "_id" : ObjectId("5a66ef780fe318d00bbaf107"), "sex" : "man", "name" : "b" }
{ "_id" : ObjectId("5a66ef7d0fe318d00bbaf108"), "sex" : "man", "name" : "c" }
{ "_id" : ObjectId("5a66ef820fe318d00bbaf109"), "sex" : "man", "name" : "d" }
{ "_id" : ObjectId("5a66ef8c0fe318d00bbaf10a"), "sex" : "woman", "name" : "e" }
{ "_id" : ObjectId("5a66ef8e0fe318d00bbaf10b"), "sex" : "woman", "name" : "f" }
{ "_id" : ObjectId("5a66ef910fe318d00bbaf10c"), "sex" : "woman", "name" : "g" }
{ "_id" : ObjectId("5a66ef930fe318d00bbaf10d"), "sex" : "woman", "name" : "h" }
{ "_id" : ObjectId("5a66ef950fe318d00bbaf10e"), "sex" : "woman", "name" : "i" }
{ "_id" : ObjectId("5a66ef970fe318d00bbaf10f"), "sex" : "woman", "name" : "j" }
{ "_id" : ObjectId("5a66efab0fe318d00bbaf110"), "sex" : "no_know", "name" : "z" }
{ "_id" : ObjectId("5a66efae0fe318d00bbaf111"), "sex" : "no_know", "name" : "x" }
{ "_id" : ObjectId("5a66efb00fe318d00bbaf112"), "sex" : "no_know", "name" : "c" }

期望得到的结果
===>

{"sex": "man", "sum": 4},
{"sex": "woman", "sum": 6} // 不用统计sex === no_know的

好像是使用group by, 找了半天没找到对应的。

阅读 4.2k
1 个回答

又去仔细的翻了翻文档。 自己搞定了。
具体思路: 使用聚合

  1. 匹配相应数据
  2. 对匹配到数据进行group
  3. 统计
db.b.aggregate([
  {$match: 
    {"sex": {$in: ["man","woman"]}}
  },// match匹配sex为 man和woman
  {$group:
    {
      _id: "$sex", // 根据什么字段分组
      count: {$sum:1} // 统计其他字段,并返回count: ***
    }
  }
])
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进