Struct mongod::Updates[][src]

pub struct Updates<U: Update> {
    pub set: Option<U>,
    pub unset: Option<U>,
}
Expand description

Used for complex updates using MongoDB’s update operators.

NOTE

Not all operators are implemented yet…

Examples

Unset the age of a user.

use mongod::bson::Document;
use mongod::{AsFilter, AsUpdate, Comparator, Error, Update, Updates};
use serde::{Deserialize, Serialize};

#[derive(Bson, Mongo, Deserialize, Serialize)]
#[mongo(collection="users", field, filter)]
pub struct User {
    pub name: String,
    pub age: u32,
}

#[derive(Default)]
pub struct UserUpdate {
    pub name: Option<String>,
    pub age: Option<u32>,
}

impl Update for UserUpdate {
    fn new() -> Self {
       UserUpdate::default()
    }
    fn into_document(self) -> Result<Document, Error> {
        let mut doc = Document::new();
        if let Some(value) = self.name {
            doc.insert("name", value);
        }
        if let Some(value) = self.age {
            doc.insert("age", value);
        }
        Ok(doc)
    }
}

impl AsUpdate<UserUpdate> for User {
    fn update() -> UserUpdate {
        UserUpdate::default()
    }
    fn into_update(self) -> UserUpdate {
        UserUpdate {
            name: Some(self.name),
            age: Some(self.age),
        }
    }
}

let client = mongod::Client::default();

let mut filter = User::filter();
filter.name = Some(Comparator::Eq("foo".to_owned()));

// NOTE: Unsetting a field that is not optional or doesn't have a default will cause
// deserialisation from the database to fail.
let unset = UserUpdate {
    age: None,
    ..UserUpdate::default()
};
let updates = Updates {
    unset: Some(unset),
    ..Updates::default()
};

let _cursor = client.update::<User, _, _>(filter, updates).await.unwrap();

Fields

set: Option<U>

Sets the value of a field in a document.

unset: Option<U>

Removes the specified field from a document.

Implementations

Convert Updates into a BSON Document.

Trait Implementations

Returns the “default value” for a type. Read more

Constructs a new Filter.

Converts a Filter into a BSON Document.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

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

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

Performs the conversion.

Should always be Self

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.