Skip to content

Instantly share code, notes, and snippets.

@andreaj8
Created September 8, 2015 14:44
Show Gist options
  • Save andreaj8/cc55408a25faeb4d6306 to your computer and use it in GitHub Desktop.
Save andreaj8/cc55408a25faeb4d6306 to your computer and use it in GitHub Desktop.
parallel count query in one model for single params
// 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: {}
}
];
@andreaj8
Copy link
Author

andreaj8 commented Sep 8, 2015

Result example:

[
  {
    "gender": "male",
    "count": 1
  },
  {
    "userAgent": "Other",
    "count": 1
  },
  {
    "phoneNumber": null,
    "count": 2
  }
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment