Struct mongodb::Client

source ·
pub struct Client { /* private fields */ }
Expand description

This is the main entry point for the API. A Client is used to connect to a MongoDB cluster. By default, it will monitor the topology of the cluster, keeping track of any changes, such as servers being added or removed.

Client uses std::sync::Arc internally, so it can safely be shared across threads or async tasks. For example:

let client = Client::with_uri_str("mongodb://example.com").await?;

for i in 0..5 {
    let client_ref = client.clone();

    task::spawn(async move {
        let collection = client_ref.database("items").collection::<Document>(&format!("coll{}", i));

        // Do something with the collection
    });
}

Notes on performance

Spawning many asynchronous tasks that use the driver concurrently like this is often the best way to achieve maximum performance, as the driver is designed to work well in such situations.

Additionally, using a custom Rust type that implements Serialize and Deserialize as the generic parameter of Collection instead of bson::Document can reduce the amount of time the driver and your application spends serializing and deserializing BSON, which can also lead to increased performance.

TCP Keepalive

TCP keepalive is enabled by default with tcp_keepalive_time set to 120 seconds. The driver does not set tcp_keepalive_intvl. See the MongoDB Diagnostics FAQ keepalive section for instructions on setting these values at the system level.

Implementations§

source§

impl Client

source

pub async fn with_uri_str(uri: impl AsRef<str>) -> Result<Self>

Creates a new Client connected to the cluster specified by uri. uri must be a valid MongoDB connection string.

See the documentation on ClientOptions::parse for more details.

source

pub fn with_options(options: ClientOptions) -> Result<Self>

Creates a new Client connected to the cluster specified by options.

source

pub fn encrypted_builder( client_options: ClientOptions, key_vault_namespace: Namespace, kms_providers: impl IntoIterator<Item = (KmsProvider, Document, Option<TlsOptions>)> ) -> Result<EncryptedClientBuilder>

Available on crate feature in-use-encryption-unstable only.

Return an EncryptedClientBuilder for constructing a Client with auto-encryption enabled.

let encrypted_client = Client::encrypted_builder(
    client_options,
    key_vault_namespace,
    [(KmsProvider::Local, doc! { "key": local_key }, None)],
)?
.key_vault_client(key_vault_client)
.build()
.await?;
source

pub fn selection_criteria(&self) -> Option<&SelectionCriteria>

Gets the default selection criteria the Client uses for operations..

source

pub fn read_concern(&self) -> Option<&ReadConcern>

Gets the default read concern the Client uses for operations.

source

pub fn write_concern(&self) -> Option<&WriteConcern>

Gets the default write concern the Client uses for operations.

source

pub fn database(&self, name: &str) -> Database

Gets a handle to a database specified by name in the cluster the Client is connected to. The Database options (e.g. read preference and write concern) will default to those of the Client.

This method does not send or receive anything across the wire to the database, so it can be used repeatedly without incurring any costs from I/O.

source

pub fn database_with_options( &self, name: &str, options: DatabaseOptions ) -> Database

Gets a handle to a database specified by name in the cluster the Client is connected to. Operations done with this Database will use the options specified by options by default and will otherwise default to those of the Client.

This method does not send or receive anything across the wire to the database, so it can be used repeatedly without incurring any costs from I/O.

source

pub fn default_database(&self) -> Option<Database>

Gets a handle to the default database specified in the ClientOptions or MongoDB connection string used to construct this Client.

If no default database was specified, None will be returned.

source

pub async fn list_databases( &self, filter: impl Into<Option<Document>>, options: impl Into<Option<ListDatabasesOptions>> ) -> Result<Vec<DatabaseSpecification>>

Gets information about each database present in the cluster the Client is connected to.

source

pub async fn list_databases_with_session( &self, filter: impl Into<Option<Document>>, options: impl Into<Option<ListDatabasesOptions>>, session: &mut ClientSession ) -> Result<Vec<DatabaseSpecification>>

Gets information about each database present in the cluster the Client is connected to using the provided ClientSession.

source

pub async fn list_database_names( &self, filter: impl Into<Option<Document>>, options: impl Into<Option<ListDatabasesOptions>> ) -> Result<Vec<String>>

Gets the names of the databases present in the cluster the Client is connected to.

source

pub async fn start_session( &self, options: impl Into<Option<SessionOptions>> ) -> Result<ClientSession>

Starts a new ClientSession.

source

pub async fn watch( &self, pipeline: impl IntoIterator<Item = Document>, options: impl Into<Option<ChangeStreamOptions>> ) -> Result<ChangeStream<ChangeStreamEvent<Document>>>

Starts a new ChangeStream that receives events for all changes in the cluster. The stream does not observe changes from system collections or the “config”, “local” or “admin” databases. Note that this method (watch on a cluster) is only supported in MongoDB 4.0 or greater.

See the documentation here on change streams.

Change streams require either a “majority” read concern or no read concern. Anything else will cause a server error.

Note that using a $project stage to remove any of the _id operationType or ns fields will cause an error. The driver requires these fields to support resumability. For more information on resumability, see the documentation for ChangeStream

If the pipeline alters the structure of the returned events, the parsed type will need to be changed via ChangeStream::with_type.

source

pub async fn watch_with_session( &self, pipeline: impl IntoIterator<Item = Document>, options: impl Into<Option<ChangeStreamOptions>>, session: &mut ClientSession ) -> Result<SessionChangeStream<ChangeStreamEvent<Document>>>

Starts a new SessionChangeStream that receives events for all changes in the cluster using the provided ClientSession. See Client::watch for more information.

Trait Implementations§

source§

impl Clone for Client

source§

fn clone(&self) -> Client

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Client

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl From<Client> for Client

Available on crate features sync or tokio-sync only.
source§

fn from(async_client: AsyncClient) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same<T> for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more