【问题标题】:How to get records count based on 3 keys in mongodb using mongoose?如何使用 mongoose 根据 mongodb 中的 3 个键获取记录数?
【发布时间】:2020-01-16 05:37:53
【问题描述】:

我有一个像这样命名为referralLink 的模型

new Schema({
  referral_link: String,
  referral_code : String,
  isLink : Number,
  offer_name: String,
  offer_desc: String,
  user_email: String,
  companyId: { type : Schema.Types.ObjectId, ref : 'companies'},
  addedByAdmin: { type: Boolean, default: true },
  number_of_clicks: Number,
  referral_country: String,
  link_status: String,
  categoryId : { type: Schema.Types.ObjectId, ref: 'categories' },
  number_of_clicks : { type: Number, default: 0 },
  createdAt: String,
  updatedAt: String,
  userId: { type: Schema.Types.ObjectId, ref: 'users' } 
})

现在我想在单个 mongoose 查询中计算 已批准拒绝待处理推荐。我想要这样的结果

{
  approved : 2,
  pending : 1,
  rejected : 3
}

我如何在猫鼬中做到这一点?

【问题讨论】:

    标签: database mongodb mongoose nosql


    【解决方案1】:

    假设已批准、未决和拒绝的值在 link_status 字段中,那么这样的事情应该可以工作:

    let linkStatusSummary = referralLink.find({}, 'link_status', (err, results) => {
      let counts = {};
    
      // create an object that contains the possible values of link_status and the number of times each occurs
      for (var i = 0; i < results.length; i++) {
        let status = results[i].link_status;
        counts[status] = counts[status] ? counts[status] + 1 : 1;  // if the category is already in the object, add 1 to the count, else create a new element with count 1
      }
      return counts
    })   
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-04
      • 2020-07-19
      • 2011-11-20
      • 2013-11-06
      • 1970-01-01
      • 2019-07-17
      • 2015-10-30
      相关资源
      最近更新 更多