Created
February 2, 2025 10:13
-
-
Save ashaffah/7edf43df01bb5caf663ceb3b48018a1a to your computer and use it in GitHub Desktop.
Rust mongodb driver auto indexing helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use mongodb::{ bson::doc, options::IndexOptions, Collection, Database, IndexModel }; | |
pub async fn auto_indexing_collection<T>(db: Database, key: Vec<String>, collection_name: String) | |
where T: serde::Serialize + serde::de::DeserializeOwned + Unpin + Send + Sync | |
{ | |
let options = IndexOptions::builder().unique(true).build(); | |
let collection: Collection<T> = db.collection(&collection_name); | |
for k in key { | |
let model = IndexModel::builder() | |
.keys(doc! { k : 1 }) | |
.options(options.clone()) | |
.build(); | |
collection.create_index(model).await.expect("creating an index should succeed"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment