'Rust MongoDB set unique fields

How to set a unique field in the mongodb rust implementation? Are you supposed to use create_index()?

async fn create_id_fields(client: Client) -> Result {
     let a = doc! {"my_id" => "1"}.unwrap;
     client
         .database(DB_NAME)
         .collection(COLL_NAME_TICKET)
         .create_index(a, unique = true)
         .await;
 }

Thanks for any hint!



Solution 1:[1]

async fn create_id_fields(client: &Client) {
    let options = IndexOptions::builder().unique(true).build();
    let model = IndexModel::builder()
        .keys(doc! {"number": 1})
        .options(options)
        .build();
    client
        .database(DB_NAME)
        .collection::<Raffle>(COLL_NAME_RAFFLE)
        .create_index(model, None)
        .await
        .expect("error creating index!");
}

...so this is my solution but do i have to use the 'builder'?

Solution 2:[2]

To add to DZWG's answer, you may need to add a type to the 1.

async fn create_id_fields(client: &Client) {
    let options = IndexOptions::builder().unique(true).build();
    let model = IndexModel::builder()
        .keys(doc! {"number": 1u32})
        .options(options)
        .build();
    client
        .database(DB_NAME)
        .collection::<Raffle>(COLL_NAME_RAFFLE)
        .create_index(model, None)
        .await
        .expect("error creating index!");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DZWG
Solution 2 Mr. Brad