我在 mongo 查询的正确时间格式方面遇到问题。
我的问题是:
- Is
time.Time
mongo ISODate 对象的正确 go 类型?
- 为什么我的时间解析似乎解析完全不同的日期?
这是我正在做的事情的完整示例。
package main
import (
// "fmt"
"context"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// Here's a JSON of the record as it is in the db
// {
// "_id" : ObjectId("5fa467af036d5f46914c423c"),
// "subscriptionRuleId" : "email@email",
// "eventDateTime" : ISODate("2020-11-05T20:59:27.096+0000"),
// "eventType" : "string-with-event-type",
// "passportAtlas" : "a long string",
// "_class" : "com.proj.info.model.dto.EventLog"
// }
type eventLog struct {
SubscriptionRuleID string `json:"subscriptionRuleId,omitempty" bson:"subscriptionRuleId"`
EventType string `json:"eventType" bson:"eventType"`
EventDateTime time.Time `json:"eventDateTime" bson:"eventDateTime"`
PassportAtlas string `json:"passportAtlas" bson:"passportAtlas`
}
func main() {
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, clientOptions)
if err != nil { log.Fatal(err) }
err = client.Ping(ctx, nil)
if err != nil { log.Fatal(err) }
collection := client.Database("compose").Collection("eventLog")
df := "2006-02-04"
dateFrom, _ := time.Parse(df, "2020-11-20")
dateTo, _ := time.Parse(df, "2020-11-21")
// This does not seem to work.
// A log of the dates gives me the wrong dates
log.Printf("\nFROM: %v\nTO: %v", dateFrom, dateTo)
// OUTPUTS:
// FROM: 2020-01-09 00:20:00 +0000 UTC
// TO: 2020-01-10 00:21:00 +0000 UTC
// Notice the dates are formatted wrong in the log.
// Even though the dates are wrong, I would still match
// Records with those wrong dates as i've got tens of thousands
// over the last few years...
query := bson.M{
"eventDateTime": bson.M{
"$gte": dateFrom,
"$lt": dateTo,
},
}
cur, err := collection.Find(ctx, query)
if err != nil { log.Fatal(err) }
defer cur.Close(context.Background())
var eventLogs []eventLog
for cur.Next(ctx) {
var eventLog eventLog
cur.Decode(&eventLog)
eventLogs = append(eventLogs, eventLog)
}
if err := cur.Err(); err != nil { log.Fatal(err) }
log.Printf("num records: %v", len(eventLogs))
}