2

I have this data time in mongo collection:

{   
 ...
 "CreationDateTime" : ISODate("2017-03-06T08:16:02.930Z"),
 ...
},
....
{   
 ...
 "CreationDateTime" : ISODate("2018-03-06T08:16:04.030Z"),
 ...
},...

I want to grouping my collection by hour. Means i want to those documents are in 8 o'clock comes in same group and those documents are in 9 o'clock comes in same group. because i want to select first document in same group. Someone have any logic or idea for this grouping with it's accumulator Operator?

Cyrus the Great
  • 5,145
  • 5
  • 68
  • 149

3 Answers3

5

If you want only particular hour then you can use $hour in aggregation framework, like below:

db.col.aggregate([
    {
        $group: {
            _id: { $hour: "$CreationDateTime" },
            docs: { $push: "$$ROOT" }
        }
    }
])

MongoDB will set 8 as a grouping _id for your docs. Otherwise if you need one hour as an interval, you have to use $dayOfMonth, $month and $years like below

db.col.aggregate([
    {
        $group: {
            _id: {
                h: { $hour: "$CreationDateTime" },
                d: { $dayOfMonth: "$CreationDateTime" } ,
                m: { $month: "$CreationDateTime" } ,
                y: { $year: "$CreationDateTime" } ,
            },
            docs: { $push: "$$ROOT" },
            firstDoc: { $first: "$$ROOT" }
        }
    }
])

And in that case you're gonna get { "h" : 8, "d" : 6, "m" : 3, "y" : 2017 } as a grouping _id

mickl
  • 48,568
  • 9
  • 60
  • 89
  • Thanks dude. I do this way but why my result is not sorted: http://codepad.org/eRQBKY4P this my code: http://codepad.org/G4gIJ8MW ....And how could i get first element of each `docs` in document to sending next stage in my pipeline? @micki – Cyrus the Great Apr 28 '18 at 03:10
  • @sayreskabir simply add firstDoc: `{ $first: "$$ROOT" }` like in my edited answer – mickl Apr 28 '18 at 04:59
0

you can mapReduce utility like

db.collection.mapReduce(function(){

  var hour = this.CreationDateTime.getHour()
  emit(this.hour,this)
},function(key,values){
 return JSON.stringify(values);
},{out:{inline:true}});
Ahmed Kesha
  • 810
  • 5
  • 11
0

**this is an aggregate framework solution. **

db.collection.aggregate(
       [
         {
           $group:
             {
               _id: "$CreationDateTime",
               items: { $push:  { field1: "$field1", field2: "$field1" } }
             }
         }
       ]
    )
Youba
  • 2,636
  • 3
  • 11
  • 25
Ahmed Kesha
  • 810
  • 5
  • 11