mongcxx and get_timestamp

250 views
Skip to first unread message

Jeff Abrahamson

unread,
Aug 21, 2018, 7:29:30 AM8/21/18
to mongodb-user
I'm having a bit of trouble with timestamps in mongocxx.  (I know that object creation time is encoded in the oid.)

I have an object that looks like this in the mongo shell:

...
"server_time" : ISODate("2016-11-17T21:47:07.141Z"),
...


and in C++ when I say

LOG_INFO << bsoncxx::to_json(doc);

I see this (newlines added here for readability):

{ "_id" : { "$oid" : "..." },
  ...,
  "server_time" : { "$date" : 1479419227141 }
}

So I try

doc["server_time"].get_timestamp().timestamp

and get an exception, "expected element type k_timestamp".  So maybe it just looks like a timestamp but isn't.  No worries, I'll try this:

doc["server_time"]["$date"].get_int64().value / 1000

and now I throw with message "unset document::element".

Can anyone point me to what mongocxx is hoping for here?

Thanks.

Andrew Morrow

unread,
Aug 21, 2018, 10:19:04 AM8/21/18
to mongod...@googlegroups.com

Hi Jeff -

Yeah, I can see how that would be confusing. What I recommend doing here is printing the actual type of the server_time field. I think you will find that it is actually of type date, rather than timestamp. Try extracting it as doc["server_time"].get_date() and see if things work better. I suspect that the $date in the JSON output isn't real - it is simply how the underlying C driver's JSON support choses to identify the field as a date type.

Thanks,
Andrew


--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: https://docs.mongodb.com/manual/support/
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at https://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/70ab4dcf-8172-4572-9378-6cd428c3a9e7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jeff Abrahamson

unread,
Aug 21, 2018, 10:49:03 AM8/21/18
to mongodb-user
Ah, yes, that's it.  Thanks, Andrew.

For future readers of this thread, I needed to write this to get seconds since the epoch:

std::chrono::duration_cast<std::chrono::seconds>(
    doc["server_time"].get_date().value
).count()


Jeff Abrahamson
Reply all
Reply to author
Forward
0 new messages