2
{

    {
    "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
    }

}

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.

I have tried this...

{
    {
        "$group": {
            "_id": {
                "description": "$description",
                "date": "$date"   
            },
            "count": {
                "$sum": 1
            }
        }
    }
}
Pablo.K
  • 1,041
  • 2
  • 10
  • 15

2 Answers2

8

With aggregate:

db.collection.aggregate(
    // Pipeline
    [
        {
            $group: {
                _id: "$date"
            }
        },
        {
            $group: {
               _id:1, 
               count: {$sum : 1 }
            }
        },
    ]
)
Marco
  • 741
  • 3
  • 18
  • This looks similar to what I did above? – Pablo.K Sep 14 '17 at 13:52
  • No, that's not the same thing. With the first pipeline operation, group by data, with the second operation counting the results. – Marco Sep 14 '17 at 13:59
  • And this counts the double dates as 1 (ie: 2017-09-06). So the count I am looking for is 6 because 2017-09-06 shows up twice. – Pablo.K Sep 14 '17 at 14:02
6

use distinct to get unique values

db.getCollection('books').distinct('date')

if you want total number of unique values

db.getCollection('books').distinct('date').length
Vignesh
  • 1,140
  • 1
  • 9
  • 17