mongo-collection 0.3.2

A trait and derive macro for mapping Rust types to MongoDB collections with automatic pluralization
Documentation
use mongodb::bson::{Bson, DateTime, Document, doc};
pub struct UpdateBuilder {
    set_doc: Document,
    set_on_insert_doc: Document,
    unset_doc: Document,
    inc_doc: Document,
    mul_doc: Document,
    min_doc: Document,
    max_doc: Document,
    push_doc: Document,
    pull_doc: Document,
    add_to_set_doc: Document,
    pop_doc: Document,
    rename_doc: Document,
    current_date_doc: Document,
}

impl UpdateBuilder {
    pub fn new() -> Self {
        Self {
            set_doc: doc! {},
            set_on_insert_doc: doc! {},
            unset_doc: doc! {},
            inc_doc: doc! {},
            mul_doc: doc! {},
            min_doc: doc! {},
            max_doc: doc! {},
            push_doc: doc! {},
            pull_doc: doc! {},
            add_to_set_doc: doc! {},
            pop_doc: doc! {},
            rename_doc: doc! {},
            current_date_doc: doc! {},
        }
    }

    // 设置字段(如果有值)
    pub fn set_if_some(mut self, field: &str, value: Option<impl Into<Bson>>) -> Self {
        if let Some(v) = value {
            self.set_doc.insert(field, v.into());
        }
        self
    }

    // 强制设置字段
    pub fn set(mut self, field: &str, value: impl Into<Bson>) -> Self {
        self.set_doc.insert(field, value.into());
        self
    }

    // 删除字段
    pub fn unset(mut self, field: &str) -> Self {
        self.unset_doc.insert(field, "");
        self
    }

    // 自动添加 updated_at
    pub fn with_timestamp(mut self) -> Self {
        self.set_doc.insert("updated_at", DateTime::now());
        self
    }

    // ========== $setOnInsert 操作符 ==========

    /// 仅在插入时设置字段 $setOnInsert
    ///
    /// 用于 upsert 操作,只在文档首次插入时设置字段值,更新时不会修改
    ///
    /// # 示例
    /// ```ignore
    /// let update = UpdateBuilder::new()
    ///     .set("name", "John")                    // 总是设置
    ///     .set_on_insert("created_at", DateTime::now())  // 仅插入时设置
    ///     .set_on_insert("credits", 100)          // 仅插入时设置
    ///     .build();
    /// ```
    pub fn set_on_insert(mut self, field: &str, value: impl Into<Bson>) -> Self {
        self.set_on_insert_doc.insert(field, value.into());
        self
    }

    /// 仅在插入时设置字段(Option 版本)
    ///
    /// 如果值为 Some,则添加到 $setOnInsert;如果为 None,则跳过
    ///
    /// # 示例
    /// ```ignore
    /// let update = UpdateBuilder::new()
    ///     .set_on_insert_if_some("referrer", user.referrer.as_ref())
    ///     .build();
    /// ```
    pub fn set_on_insert_if_some(mut self, field: &str, value: Option<impl Into<Bson>>) -> Self {
        if let Some(v) = value {
            self.set_on_insert_doc.insert(field, v.into());
        }
        self
    }

    /// 批量设置仅插入时的字段
    ///
    /// # 示例
    /// ```ignore
    /// let insert_fields = doc! {
    ///     "created_at": DateTime::now(),
    ///     "credits": 100,
    ///     "status": "active"
    /// };
    ///
    /// let update = UpdateBuilder::new()
    ///     .set("name", "John")
    ///     .set_on_insert_many(insert_fields)
    ///     .build();
    /// ```
    pub fn set_on_insert_many(mut self, fields: Document) -> Self {
        for (key, value) in fields {
            self.set_on_insert_doc.insert(key, value);
        }
        self
    }

    // ========== 数值操作符 ==========

    // 增加字段值 $inc
    pub fn inc(mut self, field: &str, amount: impl Into<Bson>) -> Self {
        self.inc_doc.insert(field, amount.into());
        self
    }

    // 乘以字段值 $mul
    pub fn mul(mut self, field: &str, multiplier: impl Into<Bson>) -> Self {
        self.mul_doc.insert(field, multiplier.into());
        self
    }

    // 更新为最小值 $min
    pub fn min(mut self, field: &str, value: impl Into<Bson>) -> Self {
        self.min_doc.insert(field, value.into());
        self
    }

    // 更新为最大值 $max
    pub fn max(mut self, field: &str, value: impl Into<Bson>) -> Self {
        self.max_doc.insert(field, value.into());
        self
    }

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

    // 向数组添加元素 $push
    pub fn push(mut self, field: &str, value: impl Into<Bson>) -> Self {
        self.push_doc.insert(field, value.into());
        self
    }

    // 向数组批量添加元素 $push + $each
    pub fn push_each<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.push_doc.insert(field, doc! { "$each": bson_values });
        self
    }

    // 从数组移除元素 $pull
    pub fn pull(mut self, field: &str, condition: impl Into<Bson>) -> Self {
        self.pull_doc.insert(field, condition.into());
        self
    }

    // 向数组添加唯一元素 $addToSet
    pub fn add_to_set(mut self, field: &str, value: impl Into<Bson>) -> Self {
        self.add_to_set_doc.insert(field, value.into());
        self
    }

    // 向数组批量添加唯一元素 $addToSet + $each
    pub fn add_to_set_each<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.add_to_set_doc
            .insert(field, doc! { "$each": bson_values });
        self
    }

    // 移除数组第一个元素 $pop: -1
    pub fn pop_first(mut self, field: &str) -> Self {
        self.pop_doc.insert(field, -1);
        self
    }

    // 移除数组最后一个元素 $pop: 1
    pub fn pop_last(mut self, field: &str) -> Self {
        self.pop_doc.insert(field, 1);
        self
    }

    // ========== 其他操作符 ==========

    // 重命名字段 $rename
    pub fn rename(mut self, old_field: &str, new_field: &str) -> Self {
        self.rename_doc.insert(old_field, new_field);
        self
    }

    // 设置为当前日期 $currentDate (boolean)
    pub fn set_current_date(mut self, field: &str) -> Self {
        self.current_date_doc.insert(field, true);
        self
    }

    // 设置为当前时间戳 $currentDate (type: "timestamp")
    pub fn set_current_timestamp(mut self, field: &str) -> Self {
        self.current_date_doc
            .insert(field, doc! { "$type": "timestamp" });
        self
    }

    // ========== 批量操作 ==========

    // 批量设置多个字段
    pub fn set_many(mut self, fields: Document) -> Self {
        for (key, value) in fields {
            self.set_doc.insert(key, value);
        }
        self
    }

    // 批量删除多个字段
    pub fn unset_many(mut self, fields: Vec<&str>) -> Self {
        for field in fields {
            self.unset_doc.insert(field, "");
        }
        self
    }

    // 构建最终更新文档
    pub fn build(self) -> Document {
        let mut update = doc! {};

        if !self.set_doc.is_empty() {
            update.insert("$set", self.set_doc);
        }

        if !self.set_on_insert_doc.is_empty() {
            update.insert("$setOnInsert", self.set_on_insert_doc);
        }

        if !self.unset_doc.is_empty() {
            update.insert("$unset", self.unset_doc);
        }

        if !self.inc_doc.is_empty() {
            update.insert("$inc", self.inc_doc);
        }

        if !self.mul_doc.is_empty() {
            update.insert("$mul", self.mul_doc);
        }

        if !self.min_doc.is_empty() {
            update.insert("$min", self.min_doc);
        }

        if !self.max_doc.is_empty() {
            update.insert("$max", self.max_doc);
        }

        if !self.push_doc.is_empty() {
            update.insert("$push", self.push_doc);
        }

        if !self.pull_doc.is_empty() {
            update.insert("$pull", self.pull_doc);
        }

        if !self.add_to_set_doc.is_empty() {
            update.insert("$addToSet", self.add_to_set_doc);
        }

        if !self.pop_doc.is_empty() {
            update.insert("$pop", self.pop_doc);
        }

        if !self.rename_doc.is_empty() {
            update.insert("$rename", self.rename_doc);
        }

        if !self.current_date_doc.is_empty() {
            update.insert("$currentDate", self.current_date_doc);
        }

        update
    }
}

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