use crate::aggregate::LookupBuilder;
use crate::Collection;
use mongodb::bson::{doc, Document};
use mongodb::Database;
use std::marker::PhantomData;
pub struct AggregateBuilder<T> {
pipeline: Vec<Document>,
_phantom: PhantomData<T>,
}
impl<T: Collection> AggregateBuilder<T> {
pub fn new() -> Self {
Self {
pipeline: Vec::new(),
_phantom: PhantomData,
}
}
pub fn match_stage(mut self, filter: Document) -> Self {
self.pipeline.push(doc! { "$match": filter });
self
}
pub fn lookup(mut self, lookup: LookupBuilder) -> Self {
let stages = lookup.build();
self.pipeline.extend(stages);
self
}
pub fn unwind(mut self, field: &str) -> Self {
self.pipeline.push(doc! {
"$unwind": format!("${}", field)
});
self
}
pub fn unwind_preserve_null(mut self, field: &str) -> Self {
self.pipeline.push(doc! {
"$unwind": {
"path": format!("${}", field),
"preserveNullAndEmptyArrays": true
}
});
self
}
pub fn project(mut self, projection: Document) -> Self {
self.pipeline.push(doc! { "$project": projection });
self
}
pub fn sort(mut self, sort: Document) -> Self {
self.pipeline.push(doc! { "$sort": sort });
self
}
pub fn limit(mut self, limit: i64) -> Self {
self.pipeline.push(doc! { "$limit": limit });
self
}
pub fn skip(mut self, skip: u64) -> Self {
self.pipeline.push(doc! { "$skip": skip as i64 });
self
}
pub fn group(mut self, group: Document) -> Self {
self.pipeline.push(doc! { "$group": group });
self
}
pub fn add_fields(mut self, fields: Document) -> Self {
self.pipeline.push(doc! { "$addFields": fields });
self
}
pub fn count(mut self, field: &str) -> Self {
self.pipeline.push(doc! { "$count": field });
self
}
pub fn add_stage(mut self, stage: Document) -> Self {
self.pipeline.push(stage);
self
}
pub async fn execute(self, db: &Database) -> Result<Vec<Document>, mongodb::error::Error> {
let collection = T::collection(db);
let mut cursor = collection.aggregate(self.pipeline).await?;
let mut results = Vec::new();
use futures::TryStreamExt;
while let Some(doc) = cursor.try_next().await? {
results.push(doc);
}
Ok(results)
}
pub fn pipeline(&self) -> &[Document] {
&self.pipeline
}
}
impl<T: Collection> Default for AggregateBuilder<T> {
fn default() -> Self {
Self::new()
}
}