Javascript 通过为多个Id值匹配同一字段来聚合查询
我有一个预订模式,其中预订由多个客户完成Javascript 通过为多个Id值匹配同一字段来聚合查询,javascript,node.js,mongodb,mongoose,aggregation-framework,Javascript,Node.js,Mongodb,Mongoose,Aggregation Framework,我有一个预订模式,其中预订由多个客户完成 var booking = new Schema({ booking: { start_time : { type: Date }, end_time : { type: Date }, park_location_id: { type: Schema.Types.ObjectId }, clientId: { type: Schema.Types.Obj
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函数。基本上只需应用值列表,并实际使用字段值而不是分组_id的静态值。因为写入$group:{u id:id也可能是$group:{u 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
}
还要注意的是,一个显式的$and,即使您实际上有多个参数,实际上几乎从来都不需要。所有参数实际上都已经是and条件,只要为单独的键指定了条件,就不需要数组形式参数
Booking.totalCheckinReport([id1,id2,id3],function(err,result) {
// deal with response here
});