Skip to content

Latest commit

 

History

History
84 lines (68 loc) · 2.12 KB

opening_databases_in_file_systems.md

File metadata and controls

84 lines (68 loc) · 2.12 KB

Opening Databases In File Systems

We can also open a database that is stored in the file system. To do this, we use open_file of Database

let db = Database::open_file("some_file.db").unwrap();

where some_file.db is the filename of the opened database. In debug mode, this file will be created in the project root folder.

Let's try to replace open_memory with open_file in the First Example.

use polodb_core::{bson::doc, Database};

fn main() {
    let db = Database::open_file("contacts.db").unwrap();
    let contacts = db.collection("contacts");

    let john = doc! {
        "Name": "John",
        "Age": 20,
    };

    contacts.insert_one(john).unwrap();

    let people = contacts.find(None).unwrap();
    for person in people {
        println!("{:#?}", person.unwrap());
    }
}

After running the program, we get the output:

Document({
    "Name": String(
        "John",
    ),
    "Age": Int32(
        20,
    ),
    "_id": ObjectId(
        "66c32ee1144f3bb99d9aa078",
    ),
})

We can also see that the file contacts.db is created. By re-running the program, we should see from the output that there are two documents.

Document({
    "Name": String(
        "John",
    ),
    "Age": Int32(
        20,
    ),
    "_id": ObjectId(
        "66c32ee1144f3bb99d9aa078",
    ),
})
Document({
    "Name": String(
        "John",
    ),
    "Age": Int32(
        20,
    ),
    "_id": ObjectId(
        "66c32f081ab12fee7e1b7419",
    ),
})

This is because the program reads a document from the file that is created when we run the program at the first time, and then we insert another document at the second run.

➡️ Next: Dropping Databases

📘 Back: Table of contents