node.js - Mongodb Query error -
i have collection named configuration, configuration has ostype, want calculate ostype , group on company using solution
return configuration.distinct("ostype").then(function (name) { var types = name var groupobj = {"$group": {"_id": "$company.name"}}, projectobj = {"$project": {"_id": 0, "company": "$_id.company"}}; var grouppipeline = types.reduce(function (obj, type) { // set group pipeline object obj["$group"][type + "_count"] = { "$sum": { "$cond": [{"$eq": ["$type", type]}, 1, 0] } }; return obj; }, groupobj); return configuration.aggregate([grouppipeline]).then(function (result) { return {status: true, code: 200, message: "configuration count", data: result} });
i getting error
"message": "exception: group aggregate field name '8.1_count' cannot used because $group's field names cannot contain '.'",
this sample document
{ "_id" : objectid("57c97bd6ad85bac155aecafb"), "itbconfigurationid" : 26921, "updatedat" : isodate("2016-09-02t13:17:10.066z"), "createdat" : isodate("2016-09-02t13:17:10.066z"), "id" : "23", "name" : "dav20-pc-126.dallas.dav20.thd", "type" : "managed workstation", "locationid" : null, "ostype" : "7", "osinfo" : "home premium x64 edition service pack 1 build 7601", "company" : { "id" : 19300, "identifier" : "dav20", "name" : "davidson stewart morelock ind ins group, llc" }, "__v" : 0 }
and distinct list of ostype
[ '7', 'mac os x', '8.1', 'vista', 'xp', '2003', '2008', '2012', '8', 'linux', 'microsoft windows server 2012 r2 datacenter x64', 'microsoft windows server 2012 r2 standard x64', 'microsoft windows 7 professional x64', '', '2000', 'microsoft windows 7 professional ', 'microsoft windows 10 pro x64', 'darwin', 'microsoft windows server 2012 standard x64', 'microsoft windows server 2008 r2 standard x64', 'microsoft windows xp professional', 'microsoft windows 8.1 pro x64', 'microsoft® windows vista™ home premium x64', 'microsoft windows server 2012 datacenter x64', 'microsoft windows server 2003 small business server', 'microsoft® windows vista™ business ', 'microsoft windows 7 home premium x64', 'microsoft windows xp home edition', 'microsoft windows 8 pro x64', 'microsoft windows 7 home premium ', 'microsoft windows 8.1 x64', 'microsoft windows 10 home x64', 'microsoft windows 8.1 pro media center x64', 'microsoft windows 10 pro' ]
as error states, cannot use field names contain '.'
character within $group
pipeline fields. since generating fields dynamically, in code generates field, temporarily replace occurence of '.'
character underscore , suggest likewise space characters.
so, code dynamically returns pipeline objects should be:
var groupobj = { "$group": { "_id": "$company.name" } }; var grouppipeline = types.reduce(function(obj, type) { obj["$group"][type.replace(".", "_").replace(/\s+/g,"_") + "_count"] = { "$sum": { "$cond": [ { "$eq": [ "$ostype", type ] }, 1, 0 ] } }; return obj; }, groupobj );
Comments
Post a Comment