Adrien Chapelet
Adrien Chapelet

Reputation: 450

Updating multiple fields of a model in MongoDB with Rust

In rust, I want to update an entire model, instead of writing a query that $set for multiple fields, like that:

use mongodb::{bson, bson::doc, Client, Collection};

let collection: Collection<User> =
               client.database(DB_NAME).collection(users::REPOSITORY_NAME);
let filter = doc! {"email": new_user_copy.email};
let new_user_bson = match bson::to_bson(&new_user_copy) {
    bson::Document(doc) => doc,
    _ => unreachable!(),
};
let update = doc! {"$set": new_user_bson};
let result = collection.update_one(filter, update, None).await;

But I have the following error at compilation:

error[E0532]: expected tuple struct or tuple variant, found struct Document --> src/controllers/users.rs:82:17 | 82 | Document(doc) => doc, | ^^^^^^^^^^^^^ | ::: /Users/adrien/.cargo/registry/src/github.com-1ecc6299db9ec823/bson-2.6.1/src/document.rs:63:1 | 63 | pub struct Document { | ------------------- Document defined here | help: use struct pattern syntax instead | 82 | Document { inner } => doc, | ~~~~~~~~~~~~~~~~~~ help: consider importing one of these items instead | 1 | use crate::controllers::users::bson::Bson::Document; | 1 | use crate::controllers::users::bson::RawBson::Document; | 1 | use crate::controllers::users::bson::RawBsonRef::Document; | 1 | use mongodb::options::UpdateModifications::Document;

Upvotes: 1

Views: 433

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22316

You can update multiple fields in a single $set definition, the error you're getting is because you're using the $and operator in the update body, which is not allowed.

Just write your $set like this:

let update = doc! {"$set": {"first_name": new_user_copy.first_name, "last_name": new_user_copy.last_name}};

This will update both the first name and the last name fields.


To update all fields contained by the input you can just pass it to the $set operator, like so:

let update = doc! {"$set": new_user_copy};

Upvotes: 2

Related Questions