Docs Menu
Docs Home
/ / /
Rust Driver
/

Insert a Document

You can insert a document into a collection by calling the insert_one() method on a Collection instance.

You must insert a document of the same type that you parameterized your Collection instance with. For example, if you parameterized your collection with the MyStruct struct, pass a MyStruct instance as a parameter to the insert_one() method to insert a document. To learn more about specifying a type parameter, see the Collection Parameterization section of the Databases and Collections guide.

The insert_one() method returns an InsertOneResult type that contains the _id field of the newly inserted document.

To learn more about the insert_one() method, see the Insert Documents guide.

This example inserts a document into the restaurants collection of the sample_restaurants database. The insert_one() method inserts a document that has name, borough, and cuisine field values.

You can insert this document as an instance of the Document type or a custom data type. To specify which data type represents the collection's data, perform the following actions on the highlighted lines:

  • To access and insert collection documents as BSON documents, replace the <T> type parameter with <Document> and the <struct or doc> placeholder with insert_doc.

  • To access and insert collection documents as instances of the Restaurant struct, replace the <T> type parameter with <Restaurant> and the <struct or doc> placeholder with insert_struct. The Restaurant struct is defined at the top of the code file.

Select the Asynchronous or Synchronous tab to see the corresponding code for each runtime:

use std::env;
use mongodb::{
bson::{doc, Document},
Client,
Collection
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
borough: String,
cuisine: String,
name: String,
}
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let insert_doc = doc! {
"name": "Sea Stone Tavern",
"cuisine": "Greek",
"borough": "Queens",
};
let insert_struct = Restaurant {
name: "Sea Stone Tavern".to_string(),
cuisine: "Greek".to_string(),
borough: "Queens".to_string(),
};
// Replace <struct or doc> with the insert_struct or insert_doc variable
let res = my_coll.insert_one(<struct or doc>).await?;
println!("Inserted a document with _id: {}", res.inserted_id);
Ok(())
}
Inserted a document with _id: ObjectId("...")
use std::env;
use mongodb::{
bson::{doc, Document},
sync::{ Client, Collection }
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
borough: String,
cuisine: String,
name: String,
}
fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri)?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let insert_doc = doc! {
"name": "Sea Stone Tavern",
"cuisine": "Greek",
"borough": "Queens",
};
let insert_struct = Restaurant {
name: "Sea Stone Tavern".to_string(),
cuisine: "Greek".to_string(),
borough: "Queens".to_string(),
};
// Replace <struct or doc> with the insert_struct or insert_doc variable
let res = my_coll.insert_one(<struct or doc>).run()?;
println!("Inserted a document with _id: {}", res.inserted_id);
Ok(())
}
Inserted a document with _id: ObjectId("...")

Back

Find Multiple