如何计算MONGODB中的所有唯一值? [英] How to count all unique values In MONGODB?

查看:160
本文介绍了如何计算MONGODB中的所有唯一值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{

    {
    "date": "2017-09-04",
    "description": "DD from my employer1",
    "amount": 1000.33
    },
    {
    "date": "2017-09-06",
    "description": "DD from my employer1",
    "amount": 1000.34
    },
    {
    "date": "2017-09-06",
    "description": "DD from my employer1",
    "amount": 1000.35
    },
    {
    "date": "2017-09-07",
    "description": "DD from employer1",
    "amount": 5000.00
    },
    {
    "date": "2017-09-08",
    "description": "DD from my employer1",
    "amount": 2000.33
    },
    {
    "date": "2017-09-09",
    "description": "DD from my employer1",
    "amount": 2000.33
    },
    {
    "date": "2017-09-10",
    "description": "DD from my employer1",
    "amount": 2000.33
    }

}

我上面有这组对象,而且我正在尝试计算唯一日期的数量。有7个带有日期字段的对象,但是正如您所看到的,2017-09-06出现了两次,这意味着总共只有6天。我正在尝试对日期进行分组,但无法让mongo仅对日期进行一次计数,而将多次出现的日期视为一个日期。

I have this set of objects above, and I am trying to count the amount of unique dates. There are 7 objects with date field but as you can see 2017-09-06 shows up twice so that means that there are only a total count of 6 days. I am trying to group my date but can't get mongo to count only the dates once and treat the ones that show up more than once as just one.

尝试过这个...

{
    {
        "$group": {
            "_id": {
                "description": "$description",
                "date": "$date"   
            },
            "count": {
                "$sum": 1
            }
        }
    }
}


推荐答案

使用总计:

db.collection.aggregate(
    // Pipeline
    [
        {
            $group: {
                _id: "$date"
            }
        },
        {
            $group: {
               _id:1, 
               count: {$sum : 1 }
            }
        },
    ]
)

这篇关于如何计算MONGODB中的所有唯一值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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