Inserting current date in MongoDB

Hello. Is there a way of inserting a document with current date in a single operation? I’m using Mongo-driver.

I don’t know which type to use, and what value should i assign to Timestamp field.

I’m using Date type validation, so the value i’m looking for is like this:

type Packet struct {
	Physical_layer  Physical_layer
	Network_layer   Network_layer
	Transport_layer Transport_layer
	Timestamp   ????type    <<<----------------------

packet1 := &Packet{
		Physical_layer: Physical_layer{
			Origin:      "MAC_o",
			Destination: "MAC_d",
			Header:      3,
			Payload:     4},
		Network_layer: Network_layer{
			Origin:      "IP_o",
			Destination: "IP_d",
			Version:     4,
			Header:      1,
			Payload:     2},
		Transport_layer: Transport_layer{
			Origin:      "PORT_o",
			Destination: "PORT_d",
			Header:      23,
			Payload:     25},
		Timestamp: ????expression,    <<<----------------------

time.Time is usually how you represent times in Go. Is there any reason to not use that?

1 Like

Thanks, it worked using time.Now() after looking documentation of your reply. Also passes MongoDB validations.

PD: Do you know how to establish the correct time zone for time.Now() method? I’m getting output 3 hours ahead of my current time.

PD2: It’s my first Golang project, sorry if things are to obvious.

Is mongodb showing you the times in UTC?


When i execute the query, i’m also printing the time.Now() value:

Golang output says:
2021-03-18 12:52:45.848120799 -0300 -03 m=+0.006643606

MongoDB stored value says:
timestamp: 2021-03-18T15:52:45.848+00:00

Those times look equivalent when ignoring the monotonic correction.

The MongDB documentation:

Model Time Data


MongoDB stores times in UTC by default, and will convert any local time representations into this form. Applications that must operate or report on some unmodified local time value may store the time zone alongside the UTC timestamp, and compute the original local time in their application logic.

The Go time.Now() formatted output is local (Argentinian?, minus three hour offset from UTC) time. The MongoDB time is UTC time.

Thanks Petrus, i’ll do that.