#mongo-db #index #indexed #collection #derive #bson #mongo-indexed

macro mongo_indexed_derive

derive macro to declaratively index mongo collections

4 releases (2 breaking)

new 0.3.0 May 13, 2024
0.2.2 Jan 13, 2024
0.2.0 Nov 2, 2023
0.1.0 Nov 2, 2023

#24 in #mongodb

Download history 9/week @ 2024-02-04 19/week @ 2024-02-11 25/week @ 2024-02-18 49/week @ 2024-02-25 4/week @ 2024-03-03 1/week @ 2024-03-10 9/week @ 2024-03-17 17/week @ 2024-03-24 74/week @ 2024-03-31 40/week @ 2024-04-07 11/week @ 2024-04-14 25/week @ 2024-04-21 20/week @ 2024-04-28 24/week @ 2024-05-05 183/week @ 2024-05-12

253 downloads per month
Used in 2 crates (via mongo_indexed)

GPL-3.0-or-later

6KB
111 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

~325–790KB
~19K SLoC