9 个版本 (3 个稳定版)

2.0.1 2024 年 8 月 16 日
1.0.0 2024 年 6 月 27 日
0.3.0 2024 年 5 月 13 日
0.2.2 2024 年 1 月 13 日
0.1.1 2023 年 11 月 2 日

#652 in Rust 模式

Download history 16/week @ 2024-04-24 18/week @ 2024-05-01 153/week @ 2024-05-08 54/week @ 2024-05-15 58/week @ 2024-05-22 33/week @ 2024-05-29 62/week @ 2024-06-05 46/week @ 2024-06-12 26/week @ 2024-06-19 164/week @ 2024-06-26 43/week @ 2024-07-03 10/week @ 2024-07-10 31/week @ 2024-07-17 22/week @ 2024-07-24 29/week @ 2024-07-31 55/week @ 2024-08-07

每月 141 次下载
用于 monitor_client

GPL-3.0-or-later

9KB
156

直接在 rust 结构体上配置 mongo 索引

示例

use mongo_indexed::doc;
use mongo_indexed_derive::MongoIndexed;
use mongodb::{bson::oid::ObjectId, options::ClientOptions};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, MongoIndexed)]
#[unique_doc_index({ "username": 1, "email": 1 })]
#[collection_name(users)] // By default, this will be the name of the struct it's defined on, in this case 'User'.
pub struct User {
    #[serde(rename = "_id")]
    pub id: ObjectId,

    #[index]
    pub username: String,

    #[index]
    pub email: String,
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // instantiate your mongo client
    let mongo =
        mongodb::Client::with_options(ClientOptions::parse("mongodb://127.0.0.1:27017").await?)?;
    let db = mongo.database("my-db");

    // Since index calls are a no-op if the indexes do not change, your APIs can
    // safely use create_indexes = true even when restarting all the time. 
    // Just be careful if the indexes change and the collection is large.
    let create_indexes = true;

    // will return a handle to 'users' collection on 'my-db', which has the specified indexes created.
    let users = mongo_indexed::collection::<User>(&db, create_indexes).await?;

    let user = users.find_one(doc! { "username": "mogh" }, None).await?;
    println!("{user:?}");

    Ok(())
}

依赖项

约 15–26MB
约 403K SLoC