docs
CURD
Insert

Insert

Use insert_one to insert one document. It returns an InsertOneResult whose inserted_id field contains the document's primary key. If the document does not contain an _id field, PoloDB generates one.

Use insert_many to insert multiple documents at once. It returns an InsertManyResult whose inserted_ids field maps each input position to its primary key.

Insert one item

A collection can be parameterized with any type that implements serde::Serialize. Deriving serde::Deserialize as well lets the same type be used for queries.

use polodb_core::{CollectionT, Database};
use serde::{Deserialize, Serialize};
 
#[derive(Debug, Serialize, Deserialize)]
struct Book {
    title: String,
    author: String,
}
 
fn main() -> polodb_core::Result<()> {
    let db = Database::open_path("./polodb-data")?;
    let collection = db.collection::<Book>("books");
 
    let result = collection.insert_one(Book {
        title: "The Three-Body Problem".to_string(),
        author: "Liu Cixin".to_string(),
    })?;
 
    println!("inserted id: {:?}", result.inserted_id);
    Ok(())
}

Insert many items

use polodb_core::bson::{doc, Document};
use polodb_core::{CollectionT, Database};
 
fn main() -> polodb_core::Result<()> {
    let db = Database::open_path("./polodb-data")?;
    let collection = db.collection::<Document>("books");
    let docs = vec![
        doc! { "title": "1984", "author": "George Orwell" },
        doc! { "title": "Animal Farm", "author": "George Orwell" },
        doc! { "title": "The Great Gatsby", "author": "F. Scott Fitzgerald" },
    ];
 
    let result = collection.insert_many(docs)?;
    println!("inserted ids: {:?}", result.inserted_ids);
    Ok(())
}