所以我有一个非常简单的结构,它被持久化在MongoDB 中
type Test struct {
ID string `bson:"_id"`
Status string `bson:"status"`
TestTime time.Time `bson:"TestTime"`
}
在检索时,我想确保我没有检索任何TestTime未初始化的值,即排除丢失/零等效时间值。时间
filter := bson.M{"status": "Ready"}
关于我应该如何在这里更新我的过滤标准的任何建议
cursor, err := r.store.Db.Collection("testCollection").Find(ctx, filter)
if err != nil {
return err
}
err = cursor.All(ctx, result)
if err != nil {
return err
}
return nil
}
这取决于如何将文档插入MongoDB。
如果您使用Test
结构插入它们,而您没有更改TestTime
字段,这意味着它将具有零值time.Time
,它将被保存到MongoDB中。在MongoDB中,它的值为:
TestTime: ISODate("0001-01-01T00:00:00.000Z")
为了过滤掉这样的时间,在Go中再次使用time.Time
的零值,如下所示:
filter := bson.M{
"status": "Ready",
"TestTime": bson.M{"$ne": time.Time{}},
}
如果你以其他方式插入文档,其中TestTime
可能是null
或不存在,你可以这样解释:
filter := bson.M{
"status": "Ready",
"TestTime": bson.M{
"$nin": []any{time.Time{}, nil},
},
}