mongo-collection 0.3.3

A trait and derive macro for mapping Rust types to MongoDB collections with automatic pluralization
Documentation
use mongodb::bson::oid::ObjectId;
use mongodb::bson::{Bson, DateTime, Document, doc};
use mongodb::error::Result;

pub struct FilterBuilder {
    conditions: Vec<Document>,
}

impl FilterBuilder {
    pub fn new() -> Self {
        Self {
            conditions: Vec::new(),
        }
    }

    // 正则搜索
    pub fn with_regex(mut self, field: &str, value: Option<&str>) -> Self {
        if let Some(v) = value {
            if !v.is_empty() {
                self.conditions.push(doc! {
                    field: { "$regex": v, "$options": "i" }
                });
            }
        }
        self
    }

    // 时间范围筛选(安全版本,解析失败时跳过)
    pub fn with_date_range(mut self, field: &str, start: Option<&str>, end: Option<&str>) -> Self {
        let mut date_filter = doc! {};

        if let Some(start_str) = start {
            if let Ok(start_date) = DateTime::parse_rfc3339_str(start_str) {
                date_filter.insert("$gte", start_date);
            }
        }

        if let Some(end_str) = end {
            if let Ok(end_date) = DateTime::parse_rfc3339_str(end_str) {
                date_filter.insert("$lte", end_date);
            }
        }

        if !date_filter.is_empty() {
            self.conditions.push(doc! { field: date_filter });
        }

        self
    }

    // 时间范围筛选(严格版本,解析失败时返回错误)
    pub fn try_with_date_range(
        mut self,
        field: &str,
        start: Option<&str>,
        end: Option<&str>,
    ) -> Result<Self> {
        let mut date_filter = doc! {};

        if let Some(start_str) = start {
            let start_date = DateTime::parse_rfc3339_str(start_str)?;
            date_filter.insert("$gte", start_date);
        }

        if let Some(end_str) = end {
            let end_date = DateTime::parse_rfc3339_str(end_str)?;
            date_filter.insert("$lte", end_date);
        }

        if !date_filter.is_empty() {
            self.conditions.push(doc! { field: date_filter });
        }

        Ok(self)
    }

    // 字段匹配
    pub fn with_field(mut self, field: &str, value: Option<impl Into<Bson>>) -> Self {
        if let Some(v) = value {
            self.conditions.push(doc! { field: v.into() });
        }
        self
    }

    // ObjectId 字段(安全版本,解析失败时跳过)
    pub fn with_id_field(mut self, field: &str, id: Option<&str>) -> Self {
        if let Some(id_str) = id {
            if let Ok(oid) = ObjectId::parse_str(id_str) {
                self.conditions.push(doc! { field: oid });
            }
        }
        self
    }

    // ObjectId 字段(严格版本,解析失败时返回错误)
    pub fn try_with_id_field(mut self, field: &str, id: Option<&str>) -> Result<Self> {
        if let Some(id_str) = id {
            let oid = ObjectId::parse_str(id_str).map_err(|e| mongodb::error::Error::custom(e))?;
            self.conditions.push(doc! { field: oid });
        }
        Ok(self)
    }

    // ========== 比较操作符 ==========

    // 大于 $gt
    pub fn with_gt(mut self, field: &str, value: impl Into<Bson>) -> Self {
        self.conditions
            .push(doc! { field: { "$gt": value.into() } });
        self
    }

    // 大于等于 $gte
    pub fn with_gte(mut self, field: &str, value: impl Into<Bson>) -> Self {
        self.conditions
            .push(doc! { field: { "$gte": value.into() } });
        self
    }

    // 小于 $lt
    pub fn with_lt(mut self, field: &str, value: impl Into<Bson>) -> Self {
        self.conditions
            .push(doc! { field: { "$lt": value.into() } });
        self
    }

    // 小于等于 $lte
    pub fn with_lte(mut self, field: &str, value: impl Into<Bson>) -> Self {
        self.conditions
            .push(doc! { field: { "$lte": value.into() } });
        self
    }

    // 不等于 $ne
    pub fn with_ne(mut self, field: &str, value: impl Into<Bson>) -> Self {
        self.conditions
            .push(doc! { field: { "$ne": value.into() } });
        self
    }

    // 范围查询 (min <= field <= max)
    pub fn with_range(mut self, field: &str, min: impl Into<Bson>, max: impl Into<Bson>) -> Self {
        self.conditions.push(doc! {
            field: {
                "$gte": min.into(),
                "$lte": max.into()
            }
        });
        self
    }

    // ========== 集合操作符 ==========

    // 在集合中 $in
    pub fn with_in<T: Into<Bson>>(mut self, field: &str, values: Vec<T>) -> Self {
        let bson_values: Vec<Bson> = values.into_iter().map(|v| v.into()).collect();
        self.conditions.push(doc! { field: { "$in": bson_values } });
        self
    }

    // 不在集合中 $nin
    pub fn with_nin<T: Into<Bson>>(mut self, field: &str, values: Vec<T>) -> Self {
        let bson_values: Vec<Bson> = values.into_iter().map(|v| v.into()).collect();
        self.conditions
            .push(doc! { field: { "$nin": bson_values } });
        self
    }

    // 在 ID 集合中(便捷方法)
    pub fn with_id_in(mut self, field: &str, ids: Vec<&str>) -> Self {
        let oids: Vec<Bson> = ids
            .into_iter()
            .filter_map(|id| ObjectId::parse_str(id).ok())
            .map(|oid| oid.into())
            .collect();

        if !oids.is_empty() {
            self.conditions.push(doc! { field: { "$in": oids } });
        }
        self
    }

    // 在 ID 集合中(严格版本)
    pub fn try_with_id_in(mut self, field: &str, ids: Vec<&str>) -> Result<Self> {
        let oids: Vec<Bson> = ids
            .into_iter()
            .map(|id| ObjectId::parse_str(id).map(|oid| oid.into()))
            .collect::<std::result::Result<Vec<_>, _>>()
            .map_err(|e| mongodb::error::Error::custom(e))?;

        if !oids.is_empty() {
            self.conditions.push(doc! { field: { "$in": oids } });
        }
        Ok(self)
    }

    // ========== 逻辑操作符 ==========

    // $or 操作符 - 创建一个包含多个过滤条件的 OR 查询
    pub fn or(conditions: Vec<Document>) -> Self {
        let mut builder = Self::new();
        if !conditions.is_empty() {
            builder.conditions.push(doc! { "$or": conditions });
        }
        builder
    }

    // $or 操作符 - 使用 FilterBuilder 数组
    pub fn or_builders(builders: Vec<FilterBuilder>) -> Self {
        let conditions: Vec<Document> = builders
            .into_iter()
            .map(|b| b.build())
            .filter(|d| !d.is_empty())
            .collect();
        Self::or(conditions)
    }

    // 添加 $or 条件到现有 builder
    pub fn with_or(mut self, conditions: Vec<Document>) -> Self {
        if !conditions.is_empty() {
            self.conditions.push(doc! { "$or": conditions });
        }
        self
    }

    // $nor 操作符 - 所有条件都不满足
    pub fn nor(conditions: Vec<Document>) -> Self {
        let mut builder = Self::new();
        if !conditions.is_empty() {
            builder.conditions.push(doc! { "$nor": conditions });
        }
        builder
    }

    // $not 操作符 - 字段不满足条件
    pub fn with_not(mut self, field: &str, condition: Document) -> Self {
        self.conditions.push(doc! { field: { "$not": condition } });
        self
    }

    // ========== 存在性和类型检查 ==========

    // 字段存在性检查 $exists
    pub fn with_exists(mut self, field: &str, exists: bool) -> Self {
        self.conditions.push(doc! { field: { "$exists": exists } });
        self
    }

    // 类型检查 $type
    pub fn with_type(mut self, field: &str, bson_type: &str) -> Self {
        self.conditions.push(doc! { field: { "$type": bson_type } });
        self
    }

    // ========== 数组操作符 ==========

    // 数组包含所有值 $all
    pub fn with_all<T: Into<Bson>>(mut self, field: &str, values: Vec<T>) -> Self {
        let bson_values: Vec<Bson> = values.into_iter().map(|v| v.into()).collect();
        self.conditions
            .push(doc! { field: { "$all": bson_values } });
        self
    }

    // 数组元素匹配 $elemMatch
    pub fn with_elem_match(mut self, field: &str, condition: Document) -> Self {
        self.conditions
            .push(doc! { field: { "$elemMatch": condition } });
        self
    }

    // 数组大小 $size
    pub fn with_size(mut self, field: &str, size: i32) -> Self {
        self.conditions.push(doc! { field: { "$size": size } });
        self
    }

    // ========== 文本搜索 ==========

    // 全文搜索 $text
    pub fn with_text_search(mut self, search: &str) -> Self {
        self.conditions.push(doc! {
            "$text": {
                "$search": search
            }
        });
        self
    }

    // 全文搜索(带语言)
    pub fn with_text_search_lang(mut self, search: &str, language: &str) -> Self {
        self.conditions.push(doc! {
            "$text": {
                "$search": search,
                "$language": language
            }
        });
        self
    }

    // 构建最终 filter
    pub fn build(self) -> Document {
        match self.conditions.len() {
            0 => doc! {},
            1 => self.conditions.into_iter().next().unwrap(),
            _ => doc! { "$and": self.conditions },
        }
    }
}

impl Default for FilterBuilder {
    fn default() -> Self {
        Self::new()
    }
}