I've been away from Rust and have recently been working on a Mongodb micro service. I have hit a problem that has vexed me and not found any good documentation.
I want to update a Mongo document with a variable number of fields. The problem is that the update command is fixed and I can't vary the fields to be updated dynamically. I have tried to build the command but it hasn't worked. Ideally I would like to specify the fields to be updated from a HashMap but not found a way to populate a mongo document and provide a suitable update command. Has anyone done this? I'm sure this is a common requirement but haven't found a solution.
This is an example of how you would do it (Sorry for the formatting, I'm on the mobile):
use mongodb::bson::{Bson, Document};
let mut changes: HashMap<String, Bson> = HashMap::new();
// Build your changes
...
// Collect the changes from the hashmap into a MongoDB Document
let changes_document: Document = changes.into_iter().collect();
collection
.update_one(
doc! { "your_model_id_field": id.to_string() },
doc! { "$set": changes_document },
None,
)
.await?;
2 Likes
I factored your suggestion into my code and it worked!! Many thanks.
Since it worked for you, could you please mark their reply as the solution?
Thank you, but you marked my reply as the solution. I meant the reply from @firebits.io. I changed the solution to that reply.
1 Like