Skip to content

Instantly share code, notes, and snippets.

@RinatMullayanov
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RinatMullayanov/3c1a7d2c856074bd0f28 to your computer and use it in GitHub Desktop.
Save RinatMullayanov/3c1a7d2c856074bd0f28 to your computer and use it in GitHub Desktop.
Mongo Snippet
/*
> for(var i = 0; i < 100000; i++ ) {
db.sample.insert({"value": Math.random(1000) + 1, "date": new Date() });
}
> db.sample.findOne()
{
"_id" : ObjectId("5560cd3bf32e638da3683b38"),
"value" : 1.3218692857772112,
"tag" : "pressure"
}
*/
// select tagId _id, avg(value) avgAmount from sample
// group by tag
db.sample.aggregate(
[
{
$group: {
_id: "$tag",
avgAmount: { $avg: "$value"}
}
}
]);
// select tagId _id, avg(value) avgAmount from sample
// group by tag
// order by tagId
db.historyMeters.aggregate([
{
$group: {'_id': '$tagId', 'avgMeter': {$avg: '$value'}}
},
{
$sort: {'_id': 1}
}
])
// select tagId, avg(value) avgAmount from sample
// group by tag
// order by tagId
db.historyMeters.aggregate([
{
$group: {'_id': '$tagId', 'avgMeter': {$avg: '$value'}}
},
{
$sort: {'_id': 1}
},
{
$project: {'_id': 0, 'avgMeter': 1, 'tagId': '$_id'}
}
])
// select tagId _id, avg(value) avgAmount from sample
// where tagId = 1
// group by tag
db.historyMeters.aggregate([
{
$match: {'tagId': 1}
},
{
$group: {'_id': '$tagId', 'avgMeter': {$avg: '$value'}}
}
])
//average per hour
db.historyMeters.aggregate(
[
{
$group: {
'_id': {
'tagId': "$tagId", 'year': {$year: '$dt'}, 'month': {$month: '$dt'}, 'day': {$dayOfMonth: '$dt'}, 'hour': {$hour: '$dt'}
},
'avgMeter': {$avg: '$value'}
}
},
{
$sort: {'_id.tagId': 1, '_id.year': 1, '_id.month': 1, '_id.day': 1, '_id.hour': 1}
},
{
$project: {
'_id': 0,
'dt': { 'year': '$_id.year', 'month': '$_id.month', 'day': '$_id.day', 'hour': '$_id.hour'},
'tagId': '$_id.tagId',
'avgMeter': 1
}
}
]
)
var start = new Date();
// Some code that takes some time
db.sample.aggregate(
[
{
$group: {
_id: "$tag",
avgAmount: { $avg: "$value"}
}
}
]);
var end = new Date();
var secondsElapsed = (end - start) / 1000;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment