mongodb Mongo 计算一组文档的每个值的出现次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28013318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:15:50  来源:igfitidea点击:

Mongo count occurrences of each value for a set of documents

mongodbmongodb-query

提问by ritmatter

I have some documents like this:

我有一些这样的文件:

{
  "user": '1'
},
{ "user": '1'
},
{
  "user": '2'
},
{
  "user": '3'
}

I'd like to be able to get a set of all the different users and their respective counts, sorted in decreasing order. So my output would be something like this:

我希望能够获得一组所有不同的用户及其各自的计数,按降序排序。所以我的输出将是这样的:

{
  '1': 2,
  '2': 1,
  '3': 1
}

I think this can be done with a Mongo aggregate(), but I'm having a lot of trouble figuring out the right flow for this.

我认为这可以通过 Mongo 聚合()来完成,但是我很难找到正确的流程。

回答by Disposer

You can get result (not in your required format) via aggregation

您可以通过聚合获得结果(不是您所需的格式)

db.collection.aggregate(
   {$group : { _id : '$user', count : {$sum : 1}}}
).result

the output for your sample documents is:

示例文档的输出是:

"0" : {
    "_id" : "2",
    "count" : 1
},
"1" : {
    "_id" : "3",
    "count" : 1
},
"2" : {
    "_id" : "1",
    "count" : 2
}

回答by Reece Daniels

For anyone reading this in Jan 2019 the accepted answer does not currently work in Robo3T (returns a pipeline.length - 1error).

对于在 2019 年 1 月阅读本文的任何人,接受的答案目前在 Robo3T 中不起作用(返回pipeline.length - 1错误)。

You must:

你必须:

a) wrap the query in a set of square brackets []

a) 将查询包裹在一组方括号中 []

b) remove .resultfrom the end

b).result从末尾删除

https://github.com/Studio3T/robomongo/issues/1519#issuecomment-441348191

https://github.com/Studio3T/robomongo/issues/1519#issuecomment-441348191

Here's an update to the accepted answer by @disposer that works for me in Robo3T.

这是@disposer 接受的答案的更新,它适用于我在 Robo3T 中。

db.getCollection('collectionName').aggregate(
    [ {$group : { _id : '$user', count : {$sum : 1}}} ]
)

回答by chridam

With MongoDb 3.6 and newer, you can leverage the use of $arrayToObjectoperator and a $replaceRootpipeline to get the desired result. You would need to run the following aggregate pipeline:

使用 MongoDb 3.6 和更新版本,您可以利用$arrayToObject运算符和$replaceRoot管道的使用来获得所需的结果。您需要运行以下聚合管道:

db.collection.aggregate([
    {  "$group": {
        "_id": "$user",
        "count": { "$sum": 1 }
    } },
    { "$sort": { "_id": 1 } },
    {  "$group": {
        "_id": null,
        "counts": {
            "$push": {
                "k": "$_id",
                "v": "$count"
            }
        }
    } },
    { "$replaceRoot": {
        "newRoot": { "$arrayToObject": "$counts" }
    } }    
])

which yields

这产生

{
    "1" : 2,
    "2" : 1,
    "3" : 1
}