我有两个模式TravelRoute&机票。我试图找到Flight.fare.total_price的$ min并返回该结果,其中包含TravelRoute中的一些细节,这些细节在航班架构中被修改。我使用的是Mongo 3.4.1和Mongoose 4.8.5
const TravelRoute = new mongoose.Schema({
departureAirport: {
type: String,
required: true,
trim: true,
},
arrivalAirport: {
type: String,
required: true,
trim: true,
},
durationDays: {
type: Number
},
fromNow: {
type: Number
},
isActive: {
type: Boolean
},
class: {
type: String,
enum: ['economy', 'business', 'first', 'any']
}
}
const Flights = new mongoose.Schema({
route: {
type: mongoose.Schema.Types.ObjectId, ref: 'TravelRoute'
},
departure_date: {
type: Date
},
return_date: {
type: Date
},
fare: {
total_price: {
type: Number
}
}
}
我有以下代码:
Flights.aggregate(
{$group: {
_id: {
route: '$route',
departure_date: '$departure_date',
return_date: '$return_date'
},
total_price: {$min: '$fare.total_price'}
}
},
{$lookup: {
from: 'TravelRoute',
localField: '_id.route',
foreignField: '_id',
as: 'routes'
}},
{$unwind: '$routes'},
{$project: {
'routes.departureAirport': 1,
'routes.destinationAirport': 1,
'departure_date': 1,
'return_date': 1,
'total_price': 1,
'_id': 1
}},
{$sort: {'total_price': 1}},
function(err, cheapFlights){
if (err) {
log.error(err)
return next(new errors.InvalidContentError(err.errors.name.message))
}
res.send(cheapFlights)
next()
})
当我使用$ unwind时,上面返回一个空数组[]。当我注释掉$ unwind阶段时,它会返回以下内容:
[
{
"_id": {
"route": "58b30cac0efb1c7ebcd14e0a",
"departure_date": "2017-04-03T00:00:00.000Z",
"return_date": "2017-04-08T00:00:00.000Z"
},
"total_price": 385.6,
"routes": []
},
{
"_id": {
"route": "58ae47ddc30b175150d94eef",
"departure_date": "2017-04-03T00:00:00.000Z",
"return_date": "2017-04-10T00:00:00.000Z"
},
"total_price": 823.68,
"routes": []
}
...
我是Mongo和Mongoose的新手。令我感到困惑的是,即使我没有预测,它也会返回“路线”。即使我要求它也不会返回departure_date(etc)?我不确定我需要$ unwind因为每次飞行只有一个TravelRoute。
谢谢...
修改
这是最终的解决方案:
{$lookup: {
from: 'travelroutes', //<-- this is the collection name in the DB
localField: '_id.route',
foreignField: '_id',
as: 'routes'
}},
{$unwind: '$routes'},
{$project: {
departureAirport: '$routes.departureAirport',
arrivalAirport: '$routes.arrivalAirport',
departureDate: '$_id.departure_date',
returnDate: '$_id.return_date',
'total_price': 1,
'routeID': '$_id.route',
'_id': 0
}},
{$sort: {'total_price': 1}},