I am getting a 'sort exceeded memory limit...' error which dictates using allowDiskUse(true) in my aggregate. My problem is that I can't quite figure out where to add that to my code. I have tried adding it as an object within the pipeline and as a property in the aggregate() method call and i get an error for both at runtime.
Code is below:
server.get('/cheap-flight-by-route', function (req, res, next) {
Flights.aggregate(
{$sort: {'fare.total_price': 1}},
{$lookup: {
from: 'travelroutes',
localField: 'route',
foreignField: '_id',
as: 'routes'
}},
{$match: {
'routes._id': {$exists: true}
}},
{$group: {
_id: {
departureAirport: '$routes.departureAirport',
arrivalAirport: '$routes.arrivalAirport',
},
total_price: {$min: '$fare.total_price'},
avg_price: {$avg: '$fare.total_price'},
created: {$first: '$created'},
doc: {$first: '$$ROOT'}
}
},
{$project: {
departureAirport: {$arrayElemAt: ['$_id.departureAirport', 0]},
arrivalAirport: {$arrayElemAt: ['$_id.arrivalAirport', 0]},
created : '$created',
price: '$total_price',
averagePrice: '$avg_price',
'doc': 1,
'_id': 0
}},
{$sort: {
'created': 1,
'departureAirport': 1,
'arrivalAirport': 1
},
},
function(err, cheapFlights){
if (err) {
log.error(err)
return next(new errors.InvalidContentError(err.errors.name.message))
}
res.send(cheapFlights)
next()
}
) // <-- if I add a .allowDiskUse(true) here it throws a 'bad property' error
})