Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Aggregate in Mongo Using Only Date Part of a DateTime Property

DZone's Guide to

Aggregate in Mongo Using Only Date Part of a DateTime Property

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

If you need to do an aggregation in MongoDB on a DateTime property and you want to aggregate only by Date part, you can use a simple trick and use a filter to compose the date part before the grouping. Here is the code:

db.mycollection.aggregate(
{
    "$project" :
    {
       _id : 0,
       "datePartDay" : {"$concat" : [
           {"$substr" : [{"$dayOfMonth" : "$LastUpdate"}, 0, 2]}, "-",
           {"$substr" : [{"$month" : "$LastUpdate"}, 0, 2]}, "-",
           {"$substr" : [{"$year" : "$LastUpdate"}, 0, 4]}
      ] }
    }
},
{ "$group" :
    { "_id" : "$datePartDay", "Count" : { "$sum" : 1 } }
    }
)

Thanks to the power of aggregation framework, we can construct a pipeline where the first stage create a document with a new property that is composed only by the day-month-year. That new document can have id equal to zero if we only need a count based on that date field, or you can assign original id of the document or whatever else. The subsequent stage of the pipeline is a simple count where the id is the new field that contains only date part of the original DateTime property.


Download Modern Java EE Design Patterns: Building Scalable Architecture for Sustainable Enterprise Development.  Brought to you in partnership with Red Hat

Topics:

Published at DZone with permission of Ricci Gian Maria, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}