use bson::DecoderError;
use mongodb::options::AggregateOptions;
impl super::Database {
pub fn aggregate<R>(
&self,
collection: &str,
pipeline: Vec<bson::Document>,
options: Option<AggregateOptions>,
) -> Result<Vec<R>, DecoderError>
where
for<'r> R: serde::Deserialize<'r>,
{
let collection = self.db.collection(&String::from(collection));
match collection.aggregate(pipeline.into_iter(), options) {
Ok(cursor) => {
let mut data: Vec<R> = vec![];
for doc in cursor {
match bson::from_bson::<R>(bson::Bson::Document(doc.expect("cannot_get_doc"))) {
Ok(document) => {
data.push(document);
}
Err(e) => return Err(e),
}
}
Ok(data)
}
Err(e) => return Err(DecoderError::Unknown(e.to_string())),
}
}
}