猫鼬获得与条件的关系数

时间:2019-07-03 18:15:50

标签: node.js mongodb mongoose aggregation-framework

我有两个模式

vehicle模式:

const VehicleSchema = new Schema({
title: {
    type: String,
    required: true
},
price: {
    type: Number,
    required: true
},
);
VehicleSchema.virtual('booking', {
    ref: 'Booking',
    localField: '_id',
    foreignField: 'vehicle',
    options: {sort: {created_at: 1}}
});
export default mongoose.model('Vehicle', VehicleSchema);

Booking架构:

const BookingSchema = new Schema({
start_at:{
  type:Date,
  required:true
},
end_at:{
    type:Date,
    required:true
},
status: {
    type: String,
    enum: ["APPROVED", "REJECTED",],
    default: "REJECTED"
},
vehicle:{
    type: Schema.Types.ObjectId,
    ref: 'Vehicle'
},
});
export default mongoose.model('Booking', BookingSchema);

每个vehicle都有多个booking

我需要获取状态为rejectedapproved的所有车辆:

 [
     {
     "title":"vehicle_1",
     "price":2500,
     "rejected_count":10
     "approved_count":55
     },{ 
     "title":"vehicle_2",
     "price":2500,
     "rejected_count":15
     "approved_count":5
     },{ 
     "title":"vehicle_3",
     "price":2500,
     "rejected_count":1
     "approved_count":30
     },{ 
     "title":"vehicle_4",
     "price":2500,
     "rejected_count":5
     "approved_count":15
     },
]

1 个答案:

答案 0 :(得分:1)

您可以使用以下汇总

Vehicle.aggregate([
  { "$lookup": {
    "from": Booking.collection.name,
    "let": { "vehicle": "$_id" },
    "pipeline": [
      { "$match": {
        "$expr": { "$eq": [ "$vehicle", "$$vehicle" ] },
        "status": "APPROVED"
      }}
    ],
    "as": "approved"
  }},
  { "$lookup": {
    "from": Booking.collection.name,
    "let": { "vehicle": "$_id" },
    "pipeline": [
      { "$match": {
        "$expr": { "$eq": [ "$vehicle", "$$vehicle" ] },
        "status": "REJECTED"
      }}
    ],
    "as": "rejected"
  }},
  { "$project": {
    "rejected_count": { "$size": "$rejected" },
    "approved_count": { "$size": "$approved" },
    "title": 1,
    "price": 1
  }}
])