how to use mondodb aggregation pipeline stages
betorobson opened this issue · comments
There is a way to use MongoDB aggregation pipeline stages?
I have this pipeline stages for instance and would be nice if I would be able to use on API.
[
{
'$lookup': {
'from': 'albums',
'localField': '_id',
'foreignField': 'singer_id',
'as': 'albums'
}
}, {
'$unwind': {
'path': '$albums',
'preserveNullAndEmptyArrays': false
}
}, {
'$lookup': {
'from': 'comments',
'localField': 'albums._id',
'foreignField': 'album_id',
'as': 'albums.comment'
}
}, {
'$group': {
'_id': '$_id',
'name': {
'$first': '$name'
},
'albums': {
'$push': '$albums'
}
}
}
]
This pipeline aggregates 3 collections and return them in one request. Examples:
- singers
-
- albums
-
-
- comments
-
Currently there is no way to use a pipeline from the REST API interface, and since this could be very very dangerous to add in that layer, probably is not the best idea to use it there.
One options could be overriding the behaviour of the endpoint:
{
resources:{
singers:{
get:{
middleware:{
beforeRetrieve:(req,res,next)=>{
const db = res.locals.db // mongodb instance
db.aggregate(YOUR_PIPELINE).toArray().then((res)=>{
return res.send(res)
})
}
}
}
}
}
}