MongoDB Aggregation group and count strings -
i have problem counting different logstatusses collection. i'd following result query:
month | importername | nroferror | nrofdebug | nrofinfo | nrofwarning
so includes grouping month , importername , counting number of documents different statusses.
my mongodb collection:
{ "_id" : "8ec84cb7-5099-4a9d-be00-a40200a67c5a", "messages" : [ { "logstatus" : "error", "message" : "my test message" }, { "logstatus" : "error", "message" : "my test message" }, { "logstatus" : "error", "message" : "my test message" }, { "logstatus" : "error", "message" : "my test message" }, { "logstatus" : "error", "message" : "my test message" } ], "starttime" : new date("2014-12-15t10:06:09.00z"), "endtime" : new date("2014-12-15t13:06:09.00z"), "haserrors" : true, "haswarnings" : false, "importername" : "myimporter" }
i have following query's:
db.sessionlogitems.aggregate ([ { $project: { month :{$month : "$starttime"}, name: "$importername", status: "$messages.logstatus", _id: 0 } } ])
result:
month: 12, "name" : "importername", status: ["error", "error", "info"]
and
db.sessionlogitems.aggregate ([ { $unwind: "$messages" }, { $group: { _id: "$messages", number : {$sum : 1 }} }, { $sort: {number : -1 } } ])
result: "_id" : { "logstatus" : "warning", "message" : "my test warning" }, "number" :5 "_id" : { "logstatus" : "error", "message" : "my test message" }, "number" : 5
but can't seem figure out correct query. appreciated!
edit:
my example above 1 out of many documents. have several importers have starttime , endtime. importers have several logmessages , 4 possible logstatusses: "error", "info", "debug", "warning". i'd have overview per month , per importer how many errors, infos, debugs , warnings produced.
assuming there no overlap in "month" between starttime
, endtime
values can use starttime
value basis grouping key. of magic other "fields" comes $cond
operator decides whether count value or not:
db.sessionlogitems.aggregate([ // unwind array de-normalize documents contained { "$unwind": "$messages" }, // month , importer form grouping key { "$group": { "_id": { "month": { "$month": "$starttime" }, "importername": "$importername" }, "nroferror": { "$sum": { "$cond": [ { "$eq": [ "$messages.logstatus", "error" ] }, 1, 0 ] } }, "nrofdebug": { "$sum": { "$cond": [ { "$eq": [ "$messages.logstatus", "debug" ] }, 1, 0 ] } }, "nrofinfo": { "$sum": { "$cond": [ { "$eq": [ "$messages.logstatus", "info" ] }, 1, 0 ] } }, "nrofwarning": { "$sum": { "$cond": [ { "$eq": [ "$messages.logstatus", "warning" ] }, 1, 0 ] } } }} ])
so "status" value tested , matched or not appropriate count value added appropriate field.
Comments
Post a Comment