javascript - How to create a query in Mongoose/Mongodb to obtain this json? -


i'm trying obtain object mongodb, counting os per month:

{january: {android: 30, ios: 10, winphone: 5}, february: {android: 4, ios: 40}, etc}.

and here mongoose schema:

var myschema = new schema({   date: {type: date,  default: date.now},   os: string }); 

can give me idea? there way create single query return me entire object or should build piece piece, unifying multiple queries?

thank you!

you're better off using output structure that's more natural mongodb keys static , values contain data. can use aggregation pipeline as:

mymodel.aggregate([     // group docs month & os     {$group: {_id: {month: {$month: '$date'}, os: '$os'}, count: {$sum: 1}}},     // group again month     {$group: {_id: '$_id.month', counts: {$push: {os: '$_id.os', count: '$count'}}}},     // rename _id month     {$project: {month: '$_id', counts: 1, _id: 0}} ], callback); 

which generates output like:

{     "result" : [          {             "counts" : [                  {                     "os" : "winphone",                     "count" : 2                 },                  {                     "os" : "ios",                     "count" : 1                 },                  {                     "os" : "android",                     "count" : 2                 }             ],             "month" : 1         },          {             "counts" : [                  {                     "os" : "ios",                     "count" : 2                 },                  {                     "os" : "android",                     "count" : 1                 }             ],             "month" : 2         }     ],     "ok" : 1 } 

if want original format can post-process result reshape want.


Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -