docs
Transactions

Transactions

A transaction is a unit of work. By default, each collection operation runs in an automatically managed transaction.

When reads and writes across multiple documents or collections must be atomic, start a transaction explicitly with Database::start_transaction. Get each collection from the transaction, perform the operations, and then call commit. Call rollback instead when the changes should be discarded.

Transactions API

use polodb_core::bson::{doc, Document};
use polodb_core::{CollectionT, Database};
 
fn main() -> polodb_core::Result<()> {
    let db = Database::open_path("./polodb-data")?;
    let txn = db.start_transaction()?;
 
    // Collections obtained from `txn` participate in this transaction.
    let collection = txn.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" },
    ];
    collection.insert_many(docs)?;
 
    txn.commit()?;
    Ok(())
}