mongo-collection 0.3.4

A trait and derive macro for mapping Rust types to MongoDB collections with automatic pluralization
Documentation
use crate::aggregate::LookupBuilder;
use crate::Collection;
use mongodb::bson::{doc, Document};
use mongodb::Database;
use std::marker::PhantomData;

/// 聚合管道构建器
///
/// 提供链式 API 构建 MongoDB 聚合管道,支持多表联合查询
///
/// # 示例
///
/// ```ignore
/// use mongo_collection::aggregate::{AggregateBuilder, LookupBuilder};
/// use mongodb::bson::doc;
///
/// // 用户关联订单和个人资料
/// let results = User::aggregate(&db)
///     .match_stage(doc! { "status": "active" })
///     .lookup(
///         LookupBuilder::new("orders", "_id", "user_id", "orders")
///             .with_pipeline(vec![
///                 doc! { "$match": { "status": "completed" } }
///             ])
///     )
///     .lookup(
///         LookupBuilder::new("profiles", "_id", "user_id", "profile")
///             .unwind()
///     )
///     .project(doc! {
///         "username": 1,
///         "orders": 1,
///         "profile": 1
///     })
///     .execute()
///     .await?;
/// ```
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,
        }
    }

    /// 添加 $match 阶段,用于过滤文档
    ///
    /// # 参数
    ///
    /// * `filter` - 过滤条件文档
    ///
    /// # 示例
    ///
    /// ```ignore
    /// use mongo_collection::FilterBuilder;
    ///
    /// let builder = User::aggregate(&db)
    ///     .match_stage(
    ///         FilterBuilder::new()
    ///             .with_field("status", Some("active"))
    ///             .build()
    ///     );
    /// ```
    pub fn match_stage(mut self, filter: Document) -> Self {
        self.pipeline.push(doc! { "$match": filter });
        self
    }

    /// 添加 $lookup 阶段,用于关联其他集合
    ///
    /// # 参数
    ///
    /// * `lookup` - LookupBuilder 构建的关联配置
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let builder = User::aggregate(&db)
    ///     .lookup(
    ///         LookupBuilder::new("orders", "_id", "user_id", "orders")
    ///     );
    /// ```
    pub fn lookup(mut self, lookup: LookupBuilder) -> Self {
        let stages = lookup.build();
        self.pipeline.extend(stages);
        self
    }

    /// 添加 $unwind 阶段,用于展开数组字段
    ///
    /// # 参数
    ///
    /// * `field` - 要展开的字段名(不需要 $ 前缀)
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let builder = User::aggregate(&db)
    ///     .unwind("orders");
    /// ```
    pub fn unwind(mut self, field: &str) -> Self {
        self.pipeline.push(doc! {
            "$unwind": format!("${}", field)
        });
        self
    }

    /// 添加 $unwind 阶段(保留 null 和空数组)
    ///
    /// # 参数
    ///
    /// * `field` - 要展开的字段名(不需要 $ 前缀)
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let builder = User::aggregate(&db)
    ///     .unwind_preserve_null("orders");
    /// ```
    pub fn unwind_preserve_null(mut self, field: &str) -> Self {
        self.pipeline.push(doc! {
            "$unwind": {
                "path": format!("${}", field),
                "preserveNullAndEmptyArrays": true
            }
        });
        self
    }

    /// 添加 $project 阶段,用于字段投影
    ///
    /// # 参数
    ///
    /// * `projection` - 投影文档
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let builder = User::aggregate(&db)
    ///     .project(doc! {
    ///         "username": 1,
    ///         "email": 1,
    ///         "orderCount": { "$size": "$orders" }
    ///     });
    /// ```
    pub fn project(mut self, projection: Document) -> Self {
        self.pipeline.push(doc! { "$project": projection });
        self
    }

    /// 添加 $sort 阶段,用于排序
    ///
    /// # 参数
    ///
    /// * `sort` - 排序文档(1 为升序,-1 为降序)
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let builder = User::aggregate(&db)
    ///     .sort(doc! { "created_at": -1, "username": 1 });
    /// ```
    pub fn sort(mut self, sort: Document) -> Self {
        self.pipeline.push(doc! { "$sort": sort });
        self
    }

    /// 添加 $limit 阶段,限制结果数量
    ///
    /// # 参数
    ///
    /// * `limit` - 最大结果数量
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let builder = User::aggregate(&db)
    ///     .limit(10);
    /// ```
    pub fn limit(mut self, limit: i64) -> Self {
        self.pipeline.push(doc! { "$limit": limit });
        self
    }

    /// 添加 $skip 阶段,跳过指定数量的文档
    ///
    /// # 参数
    ///
    /// * `skip` - 要跳过的文档数量
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let builder = User::aggregate(&db)
    ///     .skip(20)
    ///     .limit(10);
    /// ```
    pub fn skip(mut self, skip: u64) -> Self {
        self.pipeline.push(doc! { "$skip": skip as i64 });
        self
    }

    /// 添加 $group 阶段,用于分组聚合
    ///
    /// # 参数
    ///
    /// * `group` - 分组文档
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let builder = Order::aggregate(&db)
    ///     .group(doc! {
    ///         "_id": "$user_id",
    ///         "total": { "$sum": "$amount" },
    ///         "count": { "$sum": 1 }
    ///     });
    /// ```
    pub fn group(mut self, group: Document) -> Self {
        self.pipeline.push(doc! { "$group": group });
        self
    }

    /// 添加 $addFields 阶段,添加或修改字段
    ///
    /// # 参数
    ///
    /// * `fields` - 要添加的字段文档
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let builder = User::aggregate(&db)
    ///     .add_fields(doc! {
    ///         "fullName": { "$concat": ["$firstName", " ", "$lastName"] }
    ///     });
    /// ```
    pub fn add_fields(mut self, fields: Document) -> Self {
        self.pipeline.push(doc! { "$addFields": fields });
        self
    }

    /// 添加 $count 阶段,统计文档数量
    ///
    /// # 参数
    ///
    /// * `field` - 存储计数结果的字段名
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let builder = User::aggregate(&db)
    ///     .match_stage(doc! { "status": "active" })
    ///     .count("total");
    /// ```
    pub fn count(mut self, field: &str) -> Self {
        self.pipeline.push(doc! { "$count": field });
        self
    }

    /// 添加自定义聚合阶段
    ///
    /// # 参数
    ///
    /// * `stage` - 自定义阶段文档
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let builder = User::aggregate(&db)
    ///     .add_stage(doc! {
    ///         "$facet": {
    ///             "byStatus": [{ "$group": { "_id": "$status", "count": { "$sum": 1 } } }]
    ///         }
    ///     });
    /// ```
    pub fn add_stage(mut self, stage: Document) -> Self {
        self.pipeline.push(stage);
        self
    }

    /// 执行聚合管道,返回 Document 数组
    ///
    /// # 参数
    ///
    /// * `db` - MongoDB 数据库引用
    ///
    /// # 返回值
    ///
    /// 返回聚合结果的 Document 数组
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let results = User::aggregate(&db)
    ///     .match_stage(doc! { "status": "active" })
    ///     .execute()
    ///     .await?;
    ///
    /// for doc in results {
    ///     println!("{:?}", doc);
    /// }
    /// ```
    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)
    }


    /// 获取当前构建的管道(用于调试)
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let builder = User::aggregate(&db)
    ///     .match_stage(doc! { "status": "active" });
    ///
    /// println!("Pipeline: {:?}", builder.pipeline());
    /// ```
    pub fn pipeline(&self) -> &[Document] {
        &self.pipeline
    }
}

impl<T: Collection> Default for AggregateBuilder<T> {
    fn default() -> Self {
        Self::new()
    }
}