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.
Example
This example inserts a document into the restaurants
collection of
the sample_restaurants
database. The example uses a Restaurant
struct that has name
, borough
, and cuisine
fields to model
documents in the collection.
The following code creates a Restaurant
instance and inserts it into
the collection.
Select the Asynchronous or Synchronous tab to see the corresponding code for each runtime:
use std::env; use mongodb::{ bson::doc, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { borough: String, cuisine: String, name: String, } async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants"); let doc = Restaurant { name: "Sea Stone Tavern".to_string(), cuisine: "Greek".to_string(), borough: "Queens".to_string(), }; let res = my_coll.insert_one(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, sync::{ Client, Collection } }; use serde::{ Deserialize, Serialize }; struct Restaurant { borough: String, cuisine: String, name: String, } fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants"); let doc = Restaurant { name: "Sea Stone Tavern".to_string(), cuisine: "Greek".to_string(), borough: "Queens".to_string(), }; let res = my_coll.insert_one(doc).run()?; println!("Inserted a document with _id: {}", res.inserted_id); Ok(()) }
Inserted a document with _id: ObjectId("...")