Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

mongoose - MongoDB count occurrences of each value from a group filtered set of documents

I want to write a MongoDB query to get the result that returns daily count amount of success and failure in 'passcheck' field.

below is my database schema and query that I am writing

field value
createdAt YYYY/MM/DD HH:MM:SS.sssZ Before/after noon - String
passCheck success or failure - String

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since you group by passCheck aslo, the result would be either success or failure. So whay=t you can do is, you can use a condition using $cond

{ $group: {
     "_id": {
         "year": {$substr: [ "$createdAt", 0, 4 ]}, 
         "month": {$substr: [ "$createdAt", 5, 2 ]}, 
         "day": {$substr: [ "$createdAt", 8, 2 ]}
     },
     "success_count": {
        $sum: {
          $cond: [{$eq: ["$passCheck", "success"]},1,0]
        }
      },
      "failure_count": {
        $sum: {
          $cond: [ { $eq: ["$passCheck", "failure" ]},1,0]
        }
      }       
   }
},
{
    "$addFields": {
      "_id.failure_count": "$failure_count",
      "_id.success_count": "$success_count",
      "failure_count": "$$REMOVE",
      "success_count": "$$REMOVE"
    }
  }

Working Mongo playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...