Created
April 25, 2014 19:05
-
-
Save logicware/11299767 to your computer and use it in GitHub Desktop.
Aggregation Query - MongoDB 2.4.9
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'); | |
var dbURL = "mongodb://localhost:27017/test"; | |
mongoose.connect(dbURL); | |
var Schema = mongoose.Schema; | |
ProductSchema = new Schema({ | |
birthdate: { type: Date, default: Date.now }, | |
purchase_date: { type: Date, default: Date.now }, | |
product: { type: String, default: "" } | |
}); | |
var Product = mongoose.model("Product", ProductSchema); | |
var year = 365 * 24 * 60 * 60 * 1000; | |
// Assuming you have some data | |
// Output will be as follows: | |
// | |
/* | |
[ { 'ages 16-29': 0, | |
'ages 30-45': 1, | |
'ages 46-65': 2, | |
'age 66+': 0, | |
product: 'bcd' }, | |
{ 'ages 16-29': 1, | |
'ages 30-45': 0, | |
'ages 46-65': 1, | |
'age 66+': 2, | |
product: 'efg' }, | |
{ 'ages 16-29': 0, | |
'ages 30-45': 0, | |
'ages 46-65': 3, | |
'age 66+': 0, | |
product: 'def' }, | |
{ 'ages 16-29': 0, | |
'ages 30-45': 1, | |
'ages 46-65': 2, | |
'age 66+': 0, | |
product: 'xyz' }, | |
{ 'ages 16-29': 1, | |
'ages 30-45': 3, | |
'ages 46-65': 0, | |
'age 66+': 1, | |
product: 'abc' } ] | |
*/ | |
// | |
Product.aggregate([ | |
{ | |
$project: { | |
_id: 0, | |
product: 1, | |
age: { $divide: [ { $subtract: [ '$purchase_date', '$birthdate' ] }, year ] } | |
} | |
}, | |
{ | |
$group: { | |
_id: '$product', | |
'ages 16-29': { | |
$sum: { | |
$cond: [ {$and: [{ $gte: [ "$age", 16 ] }, { $lt: [ "$age", 30 ] } ]}, 1, 0 ] | |
} | |
}, | |
'ages 30-45': { | |
$sum: { | |
$cond: [ {$and: [{ $gte: [ "$age", 30 ] }, { $lt: [ "$age", 46 ] } ]}, 1, 0 ] | |
} | |
}, | |
'ages 46-65': { | |
$sum: { | |
$cond: [ {$and: [{ $gte: [ "$age", 46 ] }, { $lt: [ "$age", 66 ] } ]}, 1, 0 ] | |
} | |
}, | |
'age 66+': { | |
$sum: { | |
$cond: [ { $gte: [ "$age", 66 ] } , 1, 0 ] | |
} | |
} | |
} | |
}, | |
{ | |
$project: { | |
_id: 0, | |
product: "$_id", | |
'ages 16-29': 1, | |
'ages 30-45': 1, | |
'ages 46-65': 1, | |
'age 66+': 1 | |
} | |
} | |
], function (err, data) { | |
if (err) { | |
console.log(err); | |
} else { | |
console.log(data); | |
} | |
mongoose.connection.close(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment