从mongodb中检查time.Time的零值等效性(Golang)

huangapple go评论81阅读模式
英文:

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},
	},
}

huangapple
  • 本文由 发表于 2022年8月10日 09:48:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/73299797.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定