mongo-collection 0.3.2

A trait and derive macro for mapping Rust types to MongoDB collections with automatic pluralization
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use crate::Collection;
use crate::query::SortOrder;
use crate::query::list::{ListData, ListQuery};
use crate::query::paginated::{PaginatedData, PaginatedQuery};
use crate::utils::parse_object_id;
use async_trait::async_trait;
use mongodb::bson::{Document, doc, oid::ObjectId};
use mongodb::options::{FindOneAndUpdateOptions, FindOptions, ReturnDocument, UpdateOptions};

/// 通用集合仓储 Trait
///
/// 提供基础的 CRUD 操作接口
/// 注意:所有错误使用 MongoDB 原生错误类型 `mongodb::error::Error`
#[async_trait]
pub trait CollectionRepository: Collection + Clone + Send + Sync + Unpin
where
    Self: serde::Serialize + for<'de> serde::Deserialize<'de>,
{
    // ========== 创建操作 ==========

    /// 创建单个文档
    async fn create(
        db: &mongodb::Database,
        document: &Self,
    ) -> Result<Self, mongodb::error::Error> {
        let collection = Self::collection(db);
        collection.insert_one(document).await?;
        Ok(document.clone())
    }

    /// 批量创建文档
    async fn create_many(
        db: &mongodb::Database,
        documents: Vec<Self>,
    ) -> Result<Vec<Self>, mongodb::error::Error> {
        let collection = Self::collection(db);
        collection.insert_many(&documents).await?;
        Ok(documents)
    }

    // ========== 查询操作 ==========

    /// 根据 ID 查找文档
    async fn find_by_id(
        db: &mongodb::Database,
        id: &str,
    ) -> Result<Option<Self>, mongodb::error::Error> {
        let collection = Self::collection(db);
        let oid = parse_object_id(id)?;

        collection.find_one(doc! { "_id": oid }).await
    }

    /// 根据条件查找单个文档
    async fn find_one(
        db: &mongodb::Database,
        filter: Document,
    ) -> Result<Option<Self>, mongodb::error::Error> {
        let collection = Self::collection(db);
        collection.find_one(filter).await
    }

    /// 根据条件查找多个文档
    async fn find_many(
        db: &mongodb::Database,
        filter: Document,
        options: Option<FindOptions>,
    ) -> Result<Vec<Self>, mongodb::error::Error> {
        let collection = Self::collection(db);
        let mut cursor = match options {
            None => collection.find(filter).await?,
            Some(options) => collection.find(filter).with_options(options).await?,
        };

        let mut results = Vec::new();
        use futures::TryStreamExt;
        while let Some(doc) = cursor.try_next().await? {
            results.push(doc);
        }

        Ok(results)
    }

    /// 查找所有文档
    async fn find_all(db: &mongodb::Database) -> Result<Vec<Self>, mongodb::error::Error> {
        Self::find_many(db, doc! {}, None).await
    }

    /// 分页查询
    async fn find_paginated(
        db: &mongodb::Database,
        filter: Document,
        query: &PaginatedQuery,
    ) -> Result<PaginatedData<Self>, mongodb::error::Error> {
        let collection = Self::collection(db);

        // 获取总数
        let total_count = collection.count_documents(filter.clone()).await?;

        // 构建排序选项
        let sort_doc = if let Some(ref sort_by) = query.sort_by {
            let sort_value = match query.sort_order {
                SortOrder::Asc => 1,
                SortOrder::Desc => -1,
            };
            doc! { sort_by: sort_value }
        } else {
            doc! { "_id": -1 } // 默认按 ID 降序
        };

        // 构建查询选项
        let find_options = FindOptions::builder()
            .skip(query.skip())
            .limit(query.limit())
            .sort(sort_doc)
            .build();

        // 执行查询
        let items = Self::find_many(db, filter, Some(find_options)).await?;

        // 计算总页数
        let total_pages = (total_count as f64 / query.page_size as f64).ceil() as u64;

        Ok(PaginatedData {
            items,
            total_count,
            page: query.page,
            page_size: query.page_size,
            total_pages,
        })
    }

    /// 列表查询(不分页)
    async fn find_list(
        db: &mongodb::Database,
        filter: Document,
        query: &ListQuery,
    ) -> Result<ListData<Self>, mongodb::error::Error> {
        let collection = Self::collection(db);

        // 获取总数
        let total_count = collection.count_documents(filter.clone()).await?;

        // 构建排序选项
        let sort_doc = if let Some(ref sort_by) = query.sort_by {
            let sort_value = match query.sort_order {
                SortOrder::Asc => 1,
                SortOrder::Desc => -1,
            };
            doc! { sort_by: sort_value }
        } else {
            doc! { "_id": -1 } // 默认按 ID 降序
        };

        // 构建查询选项
        let find_options = FindOptions::builder().sort(sort_doc).build();

        // 执行查询
        let items = Self::find_many(db, filter, Some(find_options)).await?;

        Ok(ListData { items, total_count })
    }

    /// 统计文档数量
    async fn count(db: &mongodb::Database, filter: Document) -> Result<u64, mongodb::error::Error> {
        let collection = Self::collection(db);
        collection.count_documents(filter).await
    }

    /// 检查文档是否存在
    async fn exists(
        db: &mongodb::Database,
        filter: Document,
    ) -> Result<bool, mongodb::error::Error> {
        Ok(Self::find_one(db, filter).await?.is_some())
    }

    // ========== 更新操作 ==========

    /// 根据 ID 更新文档
    async fn update_by_id(
        db: &mongodb::Database,
        id: &str,
        update: Document,
    ) -> Result<bool, mongodb::error::Error> {
        let collection = Self::collection(db);
        let oid = parse_object_id(id)?;

        let result = collection.update_one(doc! { "_id": oid }, update).await?;

        Ok(result.modified_count > 0)
    }

    /// 根据条件更新单个文档
    async fn update_one(
        db: &mongodb::Database,
        filter: Document,
        update: Document,
    ) -> Result<bool, mongodb::error::Error> {
        let collection = Self::collection(db);
        let result = collection.update_one(filter, update).await?;
        Ok(result.modified_count > 0)
    }

    /// 根据条件更新多个文档
    async fn update_many(
        db: &mongodb::Database,
        filter: Document,
        update: Document,
    ) -> Result<u64, mongodb::error::Error> {
        let collection = Self::collection(db);
        let result = collection.update_many(filter, update).await?;
        Ok(result.modified_count)
    }

    /// 根据多个 ID 批量更新文档
    async fn update_by_ids(
        db: &mongodb::Database,
        ids: &[String],
        update: Document,
    ) -> Result<u64, mongodb::error::Error> {
        use crate::utils::parse_object_ids;

        let oids = parse_object_ids(ids)?;
        let filter = doc! { "_id": { "$in": oids } };
        Self::update_many(db, filter, update).await
    }

    /// 查找并更新文档(返回更新后的文档)
    async fn find_one_and_update(
        db: &mongodb::Database,
        filter: Document,
        update: Document,
    ) -> Result<Option<Self>, mongodb::error::Error> {
        let collection = Self::collection(db);
        collection.find_one_and_update(filter, update).await
    }

    // ========== Upsert 操作 ==========

    /// 根据 ID 进行 upsert 操作
    ///
    /// 如果文档存在则更新,不存在则创建新文档
    ///
    /// # 参数
    /// - `id`: 文档 ID(字符串格式)
    /// - `update`: 更新文档(应使用 UpdateBuilder 构建)
    ///
    /// # 返回值
    /// - `Ok(None)` - 更新了现有文档
    /// - `Ok(Some(ObjectId))` - 插入了新文档,返回新文档的 ID
    ///
    /// # 示例
    /// ```ignore
    /// let update = UpdateBuilder::new()
    ///     .set("name", "John")
    ///     .set("email", "john@example.com")
    ///     .with_timestamp()
    ///     .build();
    ///
    /// match User::upsert_by_id(&db, "507f1f77bcf86cd799439011", update).await? {
    ///     Some(id) => println!("创建了新文档,ID: {}", id),
    ///     None => println!("更新了现有文档"),
    /// }
    /// ```
    async fn upsert_by_id(
        db: &mongodb::Database,
        id: &str,
        upsert: Document,
    ) -> Result<Option<ObjectId>, mongodb::error::Error> {
        let collection = Self::collection(db);
        let oid = parse_object_id(id)?;

        let options = UpdateOptions::builder().upsert(true).build();
        let result = collection
            .update_one(doc! { "_id": oid }, upsert)
            .with_options(options)
            .await?;

        Ok(result.upserted_id.and_then(|bson| bson.as_object_id()))
    }

    /// 根据条件进行 upsert 操作
    ///
    /// 如果匹配的文档存在则更新,不存在则插入
    ///
    /// # 参数
    /// - `filter`: 查询条件
    /// - `update`: 更新文档(应使用 UpdateBuilder 构建)
    ///
    /// # 返回值
    /// - `Ok(None)` - 更新了现有文档
    /// - `Ok(Some(ObjectId))` - 插入了新文档,返回新文档的 ID
    ///
    /// # 示例
    /// ```ignore
    /// let filter = doc! { "email": "john@example.com" };
    /// let update = UpdateBuilder::new()
    ///     .set("name", "John Doe")
    ///     .set("last_login", DateTime::now())
    ///     .with_timestamp()
    ///     .build();
    ///
    /// match User::upsert_one(&db, filter, update).await? {
    ///     Some(id) => println!("创建了新用户,ID: {}", id),
    ///     None => println!("更新了现有用户"),
    /// }
    /// ```
    async fn upsert_one(
        db: &mongodb::Database,
        filter: Document,
        upsert: Document,
    ) -> Result<Option<ObjectId>, mongodb::error::Error> {
        let collection = Self::collection(db);

        let options = UpdateOptions::builder().upsert(true).build();
        let result = collection
            .update_one(filter, upsert)
            .with_options(options)
            .await?;

        Ok(result.upserted_id.and_then(|bson| bson.as_object_id()))
    }

    /// 根据条件进行 upsert 操作(返回文档)
    ///
    /// 类似 find_one_and_update,但启用 upsert,返回更新后的文档
    ///
    /// # 参数
    /// - `filter`: 查询条件
    /// - `update`: 更新文档(应使用 UpdateBuilder 构建)
    ///
    /// # 返回值
    /// - `Ok(Some(Self))` - 返回更新后的文档(或新插入的文档)
    /// - `Ok(None)` - 理论上不会发生(upsert 总会有结果)
    ///
    /// # 示例
    /// ```ignore
    /// let filter = doc! { "username": "johndoe" };
    /// let update = UpdateBuilder::new()
    ///     .inc("login_count", 1)
    ///     .set_current_date("last_login")
    ///     .build();
    ///
    /// let user = User::find_one_and_upsert(&db, filter, update).await?;
    /// if let Some(u) = user {
    ///     println!("用户登录次数: {}", u.login_count);
    /// }
    /// ```
    async fn find_one_and_upsert(
        db: &mongodb::Database,
        filter: Document,
        upsert: Document,
    ) -> Result<Option<Self>, mongodb::error::Error> {
        let collection = Self::collection(db);

        let options = FindOneAndUpdateOptions::builder()
            .upsert(true)
            .return_document(ReturnDocument::After)
            .build();

        collection
            .find_one_and_update(filter, upsert)
            .with_options(options)
            .await
    }

    // ========== 删除操作 ==========

    /// 根据 ID 删除文档
    async fn delete_by_id(db: &mongodb::Database, id: &str) -> Result<bool, mongodb::error::Error> {
        let collection = Self::collection(db);
        let oid = parse_object_id(id)?;

        let result = collection.delete_one(doc! { "_id": oid }).await?;
        Ok(result.deleted_count > 0)
    }

    /// 根据条件删除单个文档
    async fn delete_one(
        db: &mongodb::Database,
        filter: Document,
    ) -> Result<bool, mongodb::error::Error> {
        let collection = Self::collection(db);
        let result = collection.delete_one(filter).await?;
        Ok(result.deleted_count > 0)
    }

    /// 根据条件删除多个文档
    async fn delete_many(
        db: &mongodb::Database,
        filter: Document,
    ) -> Result<u64, mongodb::error::Error> {
        let collection = Self::collection(db);
        let result = collection.delete_many(filter).await?;
        Ok(result.deleted_count)
    }

    /// 根据多个 ID 批量删除文档
    async fn delete_by_ids(
        db: &mongodb::Database,
        ids: &[String],
    ) -> Result<u64, mongodb::error::Error> {
        use crate::utils::parse_object_ids;

        let oids = parse_object_ids(ids)?;
        let filter = doc! { "_id": { "$in": oids } };
        Self::delete_many(db, filter).await
    }

    /// 查找并删除文档(返回被删除的文档)
    async fn find_one_and_delete(
        db: &mongodb::Database,
        filter: Document,
    ) -> Result<Option<Self>, mongodb::error::Error> {
        let collection = Self::collection(db);
        collection.find_one_and_delete(filter).await
    }
}