Need to aggregate by hour and $avg in MongoDB


To aggregate, use aggregate() in MongoDB. It calculates aggregate values for the data in a collection.

Let us create a collection with documents −

> db.demo544.insertOne({"DueTime":new ISODate("2020-01-10 12:10:20"),Amount:100});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8e1f029e5f92834d7f05ce")
}
> db.demo544.insertOne({"DueTime":new ISODate("2020-01-12 12:00:00"),Amount:500});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8e1f089e5f92834d7f05cf")
}
> db.demo544.insertOne({"DueTime":new ISODate("2020-01-12 12:10:20"),Amount:900});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8e1f109e5f92834d7f05d0")
}

Display all documents from a collection with the help of find() method −

> db.demo544.find();

This will produce the following output −

{ "_id" : ObjectId("5e8e1f029e5f92834d7f05ce"), "DueTime" : ISODate("2020-01-10T12:10:20Z"), "Amount" : 100 }
{ "_id" : ObjectId("5e8e1f089e5f92834d7f05cf"), "DueTime" : ISODate("2020-01-12T12:00:00Z"), "Amount" : 500 }
{ "_id" : ObjectId("5e8e1f109e5f92834d7f05d0"), "DueTime" : ISODate("2020-01-12T12:10:20Z"), "Amount" : 900 }

Following is the query to aggregate by an hour and $avg −

> db.demo544.aggregate( { "$group": { "_id": { "$hour": "$dueTime" }, "Amount": { "$avg": "$Amount" } }} )

This will produce the following output −

{ "_id" : null, "Amount" : 500 }

Updated on: 14-May-2020

414 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements