Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get distinct ISO dates by days, months, year

I want to get a distinct set of years and months for all document objects in my MongoDB.

For example, if documents have dates:

  • 2015/08/11
  • 2015/08/11
  • 2015/08/12
  • 2015/09/14
  • 2014/10/30
  • 2014/10/30
  • 2014/08/11

Return unique months and years for all documents, ex:

  • 2015/08
  • 2015/09
  • 2014/10
  • 2014/08

Schema snippet:

var myObjSchema = mongoose.Schema({
        date: Date,
        request: {
           ...

I tried using distinct against schema field date:

db.mycollection.distinct('date', {}, {})

But this gave duplicate dates. Output snippet:

ISODate("2015-08-11T20:03:42.122Z"),
ISODate("2015-08-11T20:53:31.135Z"),
ISODate("2015-08-11T21:31:32.972Z"),
ISODate("2015-08-11T22:16:27.497Z"),
ISODate("2015-08-11T22:41:58.587Z"),
ISODate("2015-08-11T23:28:17.526Z"),
ISODate("2015-08-11T23:38:45.778Z"),
ISODate("2015-08-12T06:21:53.898Z"),
ISODate("2015-08-12T13:25:33.627Z"),
ISODate("2015-08-12T14:46:59.763Z")

So the question is:

  • a: How can I accomplish the above?
  • b: Is it possible to specify which part of the date you want distinct? Like distinct('date.month'...)?

EDIT: I've found you can get these dates and such with the following query, however the results are not distinct:

db.mycollection.aggregate( 
     [ 
         { 
             $project : { 
                  month : { 
                      $month: "$date" 
                  }, 
                  year : { 
                      $year: "$date" 
                  }, 
                  day: { 
                      $dayOfMonth: "$date" 
                  } 
              }
          } 
      ] 
  );

Output: duplicates

{ "_id" : "", "month" : 7, "year" : 2015, "day" : 14 }
{ "_id" : "", "month" : 7, "year" : 2015, "day" : 15 }
{ "_id" : "", "month" : 7, "year" : 2015, "day" : 15 }
like image 628
user3871 Avatar asked Oct 13 '15 18:10

user3871


1 Answers

You need to group your document after the projection and use $addToSet accumulator operator

db.mycollection.aggregate([
    { "$project": { 
         "year": { "$year": "$date" }, 
         "month": { "$month": "$date" } 
    }},
    { "$group": { 
        "_id": null, 
        "distinctDate": { "$addToSet": { "year": "$year", "month": "$month" }}
    }}
])
like image 156
styvane Avatar answered Oct 14 '22 23:10

styvane