Search code examples
mongodbdatetimegccutcmongo-c-driver

Mongo C Driver: Insert UTC Time directly into BCON $push


I am trying to insert a UTC timestamp directly into my $push command (below). I would like to get the UTC string in the spot that currently says "UTC TIME HERE PLEASE".

update = BCON_NEW ("$push", 
      "{", 
        "folder.0.files", 
            "{", 
                "file",     BCON_UTF8 (file_id), 
                "modified", BCON_UTF8 ("UTC TIME HERE PLEASE"), 
            "}", 
    "}");

Different Way, doesn't work here

I know how to append a UTC string to a list of commands (see below), but that structure does not work in the context of the $push that I am trying to do.

update = bson_new ();
bson_append_now_utc(update, "time", -1);
mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error);

Any suggestions?

Thanks


Update

Thanks to Totonga I have tweaked my codes to:

// Current time
long            ms; // Milliseconds
time_t          s;  // Seconds
struct timespec spec;

clock_gettime(CLOCK_REALTIME, &spec);

s  = spec.tv_sec;
ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds

// Update Mongo
update = BCON_NEW ("$push", 
    "{", 
        "folder.0.files", 
            "{", 
                "file",     BCON_UTF8 (file_id),
                "modified", BCON_DATE_TIME (ms), 
            "}", 
    "}");

Which gives me an ISODate in Mongo, but it is showing the wrong date value:

"modified" : ISODate("1970-01-01T00:00:00.913+0000")


Final Update w/Working Code Using some code from this post and the suggestion of Totonga, I was able to get working codes:

// Current time
struct timeval tv;
gettimeofday(&tv, NULL);
unsigned long long millisecondsSinceEpoch =
(unsigned long long)(tv.tv_sec) * 1000 +
(unsigned long long)(tv.tv_usec) / 1000;

// add new file
update = BCON_NEW ("$push", 
    "{", 
        "folder.0.files", 
            "{", 
                "file",     BCON_UTF8 (file_id), 
                "modified", BCON_DATE_TIME (millisecondsSinceEpoch), 
            "}", 
    "}");

mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error);

Solution

  • Using some code from this post and the suggestion of Totonga, I was able to get working codes:

    // Current time
    struct timeval tv;
    gettimeofday(&tv, NULL);
    unsigned long long millisecondsSinceEpoch =
    (unsigned long long)(tv.tv_sec) * 1000 +
    (unsigned long long)(tv.tv_usec) / 1000;
    
    // add new file
    update = BCON_NEW ("$push", 
        "{", 
            "folder.0", 
                "{", 
                    "file",     BCON_UTF8 (file_id), 
                    "modified", BCON_DATE_TIME (millisecondsSinceEpoch), 
                "}", 
        "}");
    
    mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error);