英文:
Check zero Equivalent of time.Time when retrieving from mongodb Golang
问题
所以我有一个非常简单的结构体,它被持久化在MongoDB中。
type Test struct {
ID string `bson:"_id"`
Status string `bson:"status"`
TestTime time.Time `bson:"TestTime"`
}
在检索数据时,我想确保不检索任何TestTime未初始化的值,即排除缺失/零等效的time.Time值。
filter := bson.M{"status": "Ready", "TestTime": bson.M{"$ne": time.Time{}}}
你对如何更新我的筛选条件有什么建议吗?
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
英文:
So I have a very Simple Struct which is persisted in the MongoDB
type Test struct {
ID string `bson:"_id"`
Status string `bson:"status"`
TestTime time.Time `bson:"TestTime"`
}
While Retrieving I want to make sure that I am not retrieving any value whose TestTime is not initialized i.e exclude missing/zero equivalent value of time.Time
filter := bson.M{"status": "Ready"}
Any advice on how should I update my filter criteria here
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
}
答案1
得分: 2
这取决于你如何将文档插入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},
},
}
英文:
It depends on how you inserted your documents into MongoDB.
If you inserted them using your Test
struct where you did not change the TestTime
field, that means it will have the zero value of time.Time
, which will get saved into MongoDB. In MongoDB it has a value of:
TestTime: ISODate("0001-01-01T00:00:00.000Z")
To filter out such times, in Go again use the zero value of time.Time
like this:
filter := bson.M{
"status": "Ready",
"TestTime": bson.M{"$ne": time.Time{}},
}
If you inserted documents in some other way where TestTime
may be null
or non-existing, you may account for that like this:
filter := bson.M{
"status": "Ready",
"TestTime": bson.M{
"$nin": []any{time.Time{}, nil},
},
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论