简体   繁体   中英

how to count records in mongodb

I am new in mongodb. i have a simple email Schema which implemented like below :

const emailSchema = new Schema({
  from:{
    type: String
  },
  to: {
    type: String
  },
  subject: {
    type: String
  },
  content: {
    type: String
  },
  provider:{
    type: String
  },
  success:{
    type: Boolean
  }

now i want to query all email records and seprate them in two array. one for provider=x and provider = y . then count each one's success field. how can i write such query ?

If you only want to count success: true for any provider

emailSchema.aggregate([{
  $match: {
    { 'success': true }
  },
  $group: {
    _id: {
      provider: '$provider'
    }, //group by provider 
    count: {
      $sum: 1
    }
  } //sum of success fields
]);

If you only want to count success field exists or not it may be true or false for any provider

emailSchema.aggregate([{
  $match: {
    {'success': { $exists: true }}
  },
  $group: {
    _id: {
      provider: '$provider'
    }, //group by provider 
    count: {
      $sum: 1
    }
  } //sum of success fields
]);

Use aggregate query for group and count

emailSchema.aggregate([{
      $group: {
        _id: {
          provider: '$provider'
        }, //group by provider 
        count: {
          $sum: '$success'
        }
      } //sum of success fields
    ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM