When creating indexes by create_index, we can pass an IndexOptions to options.
collection.create_index(IndexModel {keys: doc! {"Name": 1}, options: Some(IndexOptions {unique: Some(true), ..Default::default()})}).unwrap();In IndexOptions, we can set unique to Some(true) to require the uniqueness of the entry.
Here is the complete code:
use polodb_core::{bson::doc, Database, IndexModel, IndexOptions};
fn main() {
let db = Database::open_memory().unwrap();
let collection = db.collection("name_of_the_collection");
collection
.create_index(IndexModel {
keys: doc! {
"Name": 1,
},
options: Some(IndexOptions {
unique: Some(true),
..Default::default()
}),
})
.unwrap();
let result = collection.insert_one(doc! {"Name": "Bob"});
println!("{:?}", result);
let result = collection.insert_one(doc! {"Name": "Bob"});
println!("{:?}", result);
}Output:
Ok(InsertOneResult { inserted_id: ObjectId("66f15ee26a6ba31a4ddd7bef") })
Err(DuplicateKey(DuplicateKeyError { name: "Name_1", key: "\"Bob\"", ns: "name_of_the_collection" }))
In the example, when we add a repeated entry, it throws an error.
➡️ Next: Dropping Indexes
📘 Back: Table of contents