How to aggregate count on items that don't match in mongodb

350 views
Skip to first unread message

Bharath Keshav

unread,
Aug 1, 2018, 6:40:27 PM8/1/18
to mongodb-user

Hello,


I have a aggregation query that aggregates total open alerts over a span of last 7 days. My query works - as it retrieves counts in the last two days. However, it does not return a 0 count against those days where there is no data available. How do I go about including them as well?


My current query in run from within nodejs:



alerts.aggregate([{
            $match
: {
               
"misc.createdTime": {
                    $gt
: new Date(weekStart) // 7 days ago
               
},
                alertState
: alertState,
                alertCategory
: {'$regex': alertCategory}
           
}
       
},
       
{
            $group
: {
                _id
: {
                    $dateToString
: {
                        format
: "%Y%m%d",
                        date
: "$misc.createdTime"
                   
}
               
},
                count
: { $sum: { $cond: [ { $eq: [ "$match", "none" ] }, 0, 1 ] } } // => based on another SO answer, but doesn't seem to work.
               
// count: {
               
//     $sum: 1
               
// }
           
}
       
},
       
{
            $sort
: {
                _id
: 1
           
}
       
}
   
]).toArray();

Oleg Toropov

unread,
Aug 2, 2018, 10:48:25 PM8/2/18
to mongod...@googlegroups.com

Bharath

May be $add will work for you better?

--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: https://docs.mongodb.com/manual/support/
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user+unsubscribe@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at https://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/54cef48e-c8dd-4c84-ae93-9a65b6be4a42%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
//
// Oleg V.Toropov, MCP | oleg.t...@gmail.com
// -----------------------------------------------------------------
// I have discovered that if I read enough stuff that's over my head,
// I actually begin to understand some of it.
//

Wan Bachtiar

unread,
Aug 6, 2018, 12:57:17 AM8/6/18
to mongodb-user

it does not return a 0 count against those days where there is no data available

Hi Bharath,

Could you elaborate your case further with document examples ?
Especially to define no data available, i.e. do you mean the documents that don’t match the first $match stage ?

Please post both documents, the ones matched and the ones that don’t

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages