How to save DateTime UTC to mongo's ISODate in rust?

I have a problem to store date & time into mongoDB in Rust.
I use the official Rust mongodb Driver, chrono crate and serde serializer/deserializer

let doc = doc! {

   // this make "timestamp" to be saved as string on mongodb 
   // how to save this timestamp field as ISODate(YYYY-mm-ddTHH:MM:ssZ) ?

   "timestamp": record.stamp.format("%Y-%m-%dT%H:%M:%SZ").to_string(),

// save doc
let reply = collection
   .insert_one(doc, None)
   .map_err(|_| SomeError::FailedSaveError)?;

This documentation states that we can use bson::UtcDateTime to save the date into ISODate format.

But when I try to add the bson::UtcDateTime package

use mongodb::bson::oid::ObjectId;    // this works
use mongodb::bson::{doc};            // this works
use serde::{Deserialize, Serialize}; // this works
use mongodb::bson::UtcDateTime;      // unresolved import `mongodb::bson::UtcDateTime` no `UtcDateTime` in `bson`

How to access the UtcDateTime struct in bson ? Do I need to include separate bson crate ?


Thank you in advance.

You have to import DateTime from bson:

use mongodb::bson::DateTime;

And use this type in your model so that it can be serialized/deserialized correctly.

Ah I see .. they renamed the UtcDateTime to DateTime. I'm using "2.0.0-alpha.1" and currently there's still no documentation about this struct. The RUST-508 issue is still open

Right now, the problem turns into ^ the trait "From<mongodb::bson::DateTime>" is not implemented for "Bson"
Which I think is pretty weird since this DateTime is part of bson mod and I already use serde for RecordType struct

use mongodb::bson::DateTime;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone)]
pub struct RecordType {
    pub stamp: DateTime,
    pub user: String,

let record = RecordType {
   stamp: DateTime(Utc::now()),
   name: "foo".to_string()

let doc = doc! {
   "timestamp": record.stamp, // ^ the trait `From<mongodb::bson::DateTime>` is not implemented for `Bson`

You can't write a Document using the doc! macro. Try doing it like this instead:

let doc = bson::to_document(&record).unwrap().

I usually use doc! macro to create a doc but this also works for me.
Anyway thank you

Sorry, typing from a smartphone is hard. What I meant is that you can't use the doc! macro to create a document with a field with a Bson type. For such case, the library provides that helper function that I used in my reply above.

1 Like