docs
CURD
Insert

Insert

To insert a document, invoke the insert method. After the document is inserted, an InsertResult struct will be returned. If you don't provide a primary key, the database will create one for you and obtain it in the result.

You can also use the insert_many method to insert multiple documents at once.

Insert one item

Insert a struct which implements serde::Serialize;

use polodb_core::Database;
use serde::{Serialize, Deserialize};
 
#[derive(Debug, Serialize, Deserialize)]
struct Book {
    title: String,
    author: String,
}
 
let db = Database::open_file(db_path)?;
let collection = db.collection("books");
collection.insert_one(Book {
    title: "The Three-Body Problem".to_string(),
    author: "Liu Cixin".to_string(),
})?;

Insert many items

use polodb_core::bson::{Document, doc};
use serde::{Deserialize, Serialize};
 
// Get a handle to a collection of `Book`.
let typed_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" },
];
 
// Insert some documents into the "mydb.books" collection.
typed_collection.insert_many(docs, None)?;

A Collection can be parameterized with any type that implements the Serialize and Deserialize traits from the serde crate, not just Document:

use serde::{Deserialize, Serialize};
 
// Get a handle to a collection of `Book`.
let typed_collection = db.collection::<Book>("books");
 
let books = vec![
    Book {
        title: "The Grapes of Wrath".to_string(),
        author: "John Steinbeck".to_string(),
    },
    Book {
        title: "To Kill a Mockingbird".to_string(),
        author: "Harper Lee".to_string(),
    },
];
 
// Insert the books into "mydb.books" collection, no manual conversion to BSON necessary.
typed_collection.insert_many(books)?;
Last updated on May 12, 2023