#mongo-db #macro-derive #indexing #index #collection #indexed #user

mongo_indexed

derive macro to declaratively index mongo collections

9 releases (3 stable)

2.0.1 Aug 16, 2024
1.0.0 Jun 27, 2024
0.3.0 May 13, 2024
0.2.2 Jan 13, 2024
0.1.1 Nov 2, 2023

#752 in Rust patterns

Download history 309/week @ 2024-08-12 31/week @ 2024-08-19 28/week @ 2024-08-26 7/week @ 2024-09-02 15/week @ 2024-09-09 63/week @ 2024-09-16 77/week @ 2024-09-23 51/week @ 2024-09-30 55/week @ 2024-10-07 47/week @ 2024-10-14 48/week @ 2024-10-21 32/week @ 2024-10-28 27/week @ 2024-11-04 7/week @ 2024-11-11 24/week @ 2024-11-18 36/week @ 2024-11-25

97 downloads per month
Used in 2 crates

GPL-3.0-or-later

9KB
156 lines

Configure mongo indexing right on your rust structs

Example

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://localhost: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(())
}

Dependencies

~15–25MB
~375K SLoC