Mongodb driver for Rust
Rust is a low-level programming language with high performance. Rust is quite often used with MongoDB to write game engines and embedded applications. It also provides high level API to support common MongoDB operations.
Key features
1. It uses the bson crate for BSON support.
2. The driver support both Synchronous and Asynchronous operations.
Code example
Rust
use mongodb::{Client, options::ClientOptions}; // Define a Person struct to represent the document structure #[derive(Debug)] struct Person { name: String, age: i32, city: String, email: String, } // The main asynchronous function #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { // Set up MongoDB connection options let client_options = ClientOptions::parse( "mongodb://localhost:27017" ).await?; // Connect to MongoDB using the configured options let client = Client::with_options(client_options)?; // Access the "testdb" database and "people" collection let db = client.database( "testdb" ); let collection = db.collection::<Person>( "people" ); // Create a Person instance to insert into the collection let person = Person { name: "James" .to_string(), age: 28, city: "New York" .to_string(), email: "James@example.com" .to_string(), }; // Insert the Person document into the collection collection.insert_one(person.clone(), None).await?; // Print a message indicating that the document was inserted println!( "Inserted document: {:?}" , person); // Query the database to find the inserted document let filter = mongodb::bson::doc! { "name" : "James" }; if let Some(result) = collection.find_one(filter, None).await? { // Print the found document println!( "Found document: {:?}" , result); } else { // Print a message if the document is not found println!( "Document not found" ); } // Return a Result indicating successful execution Ok(()) } |
Output:
Inserted document: Person { name: "James", age: 28, city: "New York", email: "James@example.com" }
Found document: Person { name: "James", age: 28, city: "New York", email: "James@example.com" }
MongoDB Drivers For Different Languages
MongoDB is a NoSQL database that is widely used for storing and managing both complex and larger data. For good integration between applications and the MongoDB database, it provides drivers that allow the developer to interact with the database using the programming language of their choice. In this article, we will see different drivers of MongoDB which are popularly used.
Programming Languages supported by MongoDB are C, C++, C#, Go, Java, Kotlin, Node.js, PHP, Python, Ruby, Rust, Scala, and Swift. We will understand each one of them more easily along with their code implementation