Created
September 8, 2015 14:44
-
-
Save andreaj8/cc55408a25faeb4d6306 to your computer and use it in GitHub Desktop.
parallel count query in one model for single params
This file contains 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
// Use MongoDB 3.0 group() function for getting users and count attribute | |
function countUsersAttributes(_key, _cond) { | |
var deferred = Q.defer(); | |
db_mongo_driver.users.group({ | |
key: _key, | |
cond: _cond, | |
reduce: function (value, result) { | |
result.count++; | |
}, | |
initial: { | |
count: 0 | |
} | |
}, function (err, countObj) { | |
if (err || !countObj) { | |
deferred.reject(err || { | |
error: 'no results' | |
}); | |
} | |
deferred.resolve(countObj[0]) | |
}); | |
return deferred.promise | |
} | |
// Prepare list of promises | |
var arrayPromises = []; | |
for (var i = 0; i < listOfQuerys.length; i++) { | |
arrayPromises.push(countUsersAttributes(listOfQuerys[i].key, listOfQuerys[i].cond)) | |
} | |
Q.all(arrayPromises).then(function (err, _res) { | |
res.status(200).jsonp(err || _res); | |
}); | |
// Use this array for add the field that you need to count, and condiction about this field if you need that | |
var listOfQuerys = [ | |
{ | |
key: { | |
gender: 1 | |
}, | |
cond: { | |
gender: { | |
$exists: true | |
} | |
} | |
}, | |
{ | |
key: { | |
userAgent: 1 | |
}, | |
cond: { | |
userAgent: { | |
$exists: true | |
} | |
} | |
}, { | |
key: { | |
phoneNumber: 1 | |
}, | |
cond: {} | |
} | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result example: