2017-08-25 45 views
0

我有一个预订模式,其中预订由多个客户端完成。通过匹配多个Id值的相同字段来合计查询

var booking = new Schema({ 
    booking: { 

     start_time : { type: Date }, 
     end_time : { type: Date }, 
     park_location_id: { type: Schema.Types.ObjectId }, 
     clientId: { type: Schema.Types.ObjectId }, 
    } 
}); 

在这里,我要寻找一个方式,我可以通过多种的clientId在数组中,并为所有这些进行汇总,并得到汇总结果在一个单一的query.Right我现在执行环路操作,获取每个客户端的结果。

booking.statics.totalCheckinReport = function(id,callback){ 
    // Here id is single client 
    // can I pass an array of clientID as [ id1, id2,id3] 
    // and get the aggregated result of all of them 
     this.aggregate([ 
      { 
       $match: 
        { 
         $and:[ 
          {'booking.park_location_id' : mongoose.Types.ObjectId(id)} 
         ] 
        } 
      }, 
      { 
       $group :{ 
        _id : id, 
        totalCheckinCount: { $sum : 1 }, 
       } 
      } 
      ]).exec(function(err, data){ 
       if(err) 
       callback(null,err); 
       else 
       callback(null, data); 
     }) 
    } 

那么有没有更好的方式来做到这一点,而不循环clientID并将它传递给我的猫鼬函数。

回答

1

基本上只是应用$in作为值列表,而实际上使用“字段值”而不是“静态值”来分组_id。因为写"$group": { "_id": id也可能是"$group": { "_id": null。你得到更多的实用了使用“域值”,而不是:

booking.statics.totalCheckinReport = function(ids,callback){ 
     // using ids as an array as input 
     ids = ids.map(id => mongoose.Types.ObjectId(id)); // Cast each array member 
     this.aggregate([ 
      { $match:{ 
      'booking.park_location_id' : { $in: ids } 
      }}, 
      { $group :{ 
      _id : '$booking.park_location_id' // <-- Actually use the field value 
      totalCheckinCount: { $sum : 1 }, 
      }} 
     ]).exec(callback)      // <-- this already passes the error 
               // and result 
    } 

调用作为

Booking.totalCheckinReport([id1,id2,id3],function(err,result) { 
    // deal with response here 
}); 

还要注意的是一个明确的$and(即使你实际上确实有多个参数)几乎是从未实际需要。所有参数实际上已经是“AND”条件,并且只要条件被指定为“单独的键”,则不需要“数组形式”参数。