We can use insert_one to insert a document to a Collection.
collection.insert_one(/* a document */).unwrap();
For creating a document, a convenient way is to use doc!. The macro doc! transforms a JSON text to a rust type.
collection.insert_one(doc! {
"Name": "John",
"Age": 21,
}).unwrap();
In the JSON text above, we have two entries: Name
and Age
, which have value John
and 21
respectively.
Here is the complete example:
use polodb_core::{bson::doc, Database};
fn main() {
let db = Database::open_memory().unwrap();
let collection = db.collection("name_of_the_collection");
let result = collection
.insert_one(doc! {
"Name": "John",
"Age": 21,
})
.unwrap();
println!("{:?}", result);
}
Output:
InsertOneResult { inserted_id: ObjectId("66b3bc1e5c6165633b65f593") }
➡️ Next: Inserting Multiple Documents
📘 Back: Table of contents