MongoDB Driver: Creating an "update statement" document (with serde)

I've got a good deal of code written against mongo using the Rust crate but have run into a bit of a problem.

I want to use update_one to do insert-or-update. The problem is that if I give the fn a serde-generated document using bson::to_bson as usual, the following error results:

"update document must have first key starting with '$"

Digging, it turns out that this functionality requires passing an update statement instead of a document. This can be done with the doc! macro easily enough, but that would be really ugly in our code base.

Looking thru the docs, I can't see a way to go from a serde Deserializable to an update statement.

Why?

Because we have huge structs and are using serde everywhere else.

Just not ideal.

I'm getting the feeling there's no other way, however.

I don't get why the size of the struct would matter? A big type can be serialized just like a small type. This snippet never needs to do anything that would depend on the size after constructing the instance (which you need to do anyway).

You can define a generic wrapper.

1 Like

Now I see what you mean!

Did you check the first piece of code?

Our replies just crossed. Yes, now I get it - we can use doc! with a pre-packaged bit of BSON. Got it!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.