Skip to content

Instantly share code, notes, and snippets.

@ashaffah
Created February 2, 2025 10:13
Show Gist options
  • Save ashaffah/7edf43df01bb5caf663ceb3b48018a1a to your computer and use it in GitHub Desktop.
Save ashaffah/7edf43df01bb5caf663ceb3b48018a1a to your computer and use it in GitHub Desktop.
Rust mongodb driver auto indexing helper
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