【问题标题】:Aggregate Query by Matching The Same field for Multiple Id Values通过匹配多个 Id 值的相同字段来聚合查询
【发布时间】:2018-02-03 06:23:20
【问题描述】:

我有一个预订模式,其中预订由多个客户完成。

    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,并为所有这些 clientId 执行聚合,并在一个查询中获取聚合结果。现在我正在执行一个循环操作来获取每个的结果客户。

    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);
         })
    }

那么有没有更好的方法来做到这一点,而无需遍历 clientsID 并将其传递给我的 mongoose 函数。

【问题讨论】:

    标签: javascript node.js mongodb mongoose aggregation-framework


    【解决方案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”条件,只要为“单独的键”指定了条件,那么就不需要“数组形式”参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-07
      • 2023-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 2021-11-03
      • 1970-01-01
      相关资源
      最近更新 更多