mongo 从提供的数据数组中计算行数 [英] mongo count rows from an array of provided data

查看:44
本文介绍了mongo 从提供的数据数组中计算行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的收藏:

{ 
   "_id" : ObjectId("4d663451d1e7242c4b68e000"), 
  "topic" : "abc", 
  "subLevel" : {
     "id" : 1
  }
}
{ 
    "_id" : ObjectId("4d6634514cb5cb2c4b69e000"), 
    "topic" : "bce", 
    "subLevel" : {
        "id" : 1
     }
}

{ 
    "_id" : ObjectId("4d6634514cb5cb2c4b70e000"), 
    "topic" : "bec", 
    "subLevel" : {
        "id" : 2
     }
}
{ 
    "_id" : ObjectId("4d6634514cb5cb2c4b70e000"), 
    "topic" : "vvv", 
    "subLevel" : {
        "id" : 3
     }
}

并且我需要计算提供的 subLevel.id 列表存在多少个文档,例如,如果我提供 1 和 2,它应该告诉我,对于 1,我们有 2 个文档,对于 2,只有 1 个文档,并且只需省略 subLevel 的文档.id 是 3,因为它不在 id 列表中.

and I need to count how many documents exist for provided subLevel.id list, for example if I provide 1 and 2 it should show me that for 1 we have 2 documents and for 2 only 1 document and simply omit document where subLevel.id is 3 as it's not in the list of id's.

我试着用聚合来做

db.getCollection('products').aggregate( [
   { $project: 
       {  "has_sublevel" : {$in: [ "subLevel.id", [1 , 2 ]]} }
   },
   { $group: { _id : "$subLevel.id", count: { $sum: 1 } } }
] )

但结果是

{
   _id : null,
   count: 4
}

我该怎么做,提前致谢!

how can I do it, thanks in advance!

如果将其转换为我更熟悉的 SQL,则查询应如下所示:

If transform it to SQL which I familiar more, query should look like this:

select subLevelId, count(id) FROM products where subLevelId in (1,2) group by subLevelId

推荐答案

如果我没理解错,你离我很近,请检查这个查询:

If I've understand correctly, you are so so close, check this query:

  • 首先使用 $match 只获取 subLevel.id 为 1 或 2 的文档.
  • 然后,正如您所做的那样,$group 通过 id 和 sum 得到总计数:
  • First use $match to get only documents whose subLevel.id is 1 or 2.
  • Then, as you have done, $group by the id and sum to get total count:
db.collection.aggregate([
  {
    "$match": { "subLevel.id": { "$in": [ 1, 2 ] } }
  },
  {
    "$group": { "_id": "$subLevel.id", "count": { "$sum": 1 } }
  }
])

示例此处

这篇关于mongo 从提供的数据数组中计算行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆