使用日期范围过滤MongoDB。

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

Go filter mongoDB by date range

问题

我正在尝试使用Golang编写一个查询,其中我将过滤出今天为特定profileId创建的操作,并给出计数。问题是我不知道如何编写一个过滤器,以过滤出特定时间范围内的项目。而且我似乎找不到一个使用Golang和MongoDB的合适解决方案。

Action结构中的时间戳字段是创建日期,必须用它来过滤出当天创建的操作。

如果有人能帮助我并指导我正确的方向,我将非常感激。谢谢。

以下是你的代码:

type Action struct {
	ID        primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
	ProfileID primitive.ObjectID `json:"profileID,omitempty" bson:"profileID,omitempty"`
	Timestamp time.Time          `json:"timestamp,omitempty" bson:"timestamp,omitempty"`
	TypeID    int                `json:"type" bson:"type"`
}

func MatchActionAmount(profileId primitive.ObjectID) (int64, error) {
	filter := bson.M{"profileID": profileId}
	count, err := getActionCountByFilter(filter)
	if err != nil {
		log.Error("Could not get action count, error:", err)
		return 0, err
	}
	return count, nil
}

func getActionCountByFilter(filter primitive.M) (int64, error) {
	ctx, _ := db.GetTimeoutContext()
	return getActionCollection().CountDocuments(ctx, filter)
}

func getActionCollection() *mongo.Collection {
	return db.GetMongoCollection("action")
}

希望对你有帮助!

英文:

I am trying to write a query using Golang where I would filter actions that where created today for a specific profileId and would give me the count. The problem is I do not know how to write a filter that would filter out items from a specific time range. And I can't seem to find a proper solution where Golang and MongoDB was used.

The timestamp field in the Action struct is the creation date that has to be used to filter out the actions that where created that day.

If anyone could help me and would put me on the right track I would greatly appreciate it. Thank you.

Here is my code:

type Action struct {
	ID        primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
	ProfileID primitive.ObjectID `json:"profileID,omitempty" bson:"profileID,omitempty"`
	Timestamp time.Time          `json:"timestamp,omitempty" bson:"timestamp,omitempty"`
	TypeID    int                `json:"type" bson:"type"`
}

func MatchActionAmount(profileId primitive.ObjectID) (int64, error) {
	filter := bson.M{"profileID": profileId}
	count, err := getActionCountByFilter(filter)
	if err != nil {
		log.Error("Could not get action count, error: ", err)
		return 0, err
	}
	return count, nil
}

func getActionCountByFilter(filter primitive.M) (int64, error) {
	ctx, _ := db.GetTimeoutContext()
	return getActionCollection().CountDocuments(ctx, filter)
}

func getActionCollection() *mongo.Collection {
	return db.GetMongoCollection("action")
}

答案1

得分: 1

如果时间戳始终是创建日期(不能是未来的时间戳),你实际上不需要一个范围(between)过滤器,你只需要记录中创建时间戳大于今天凌晨的记录。

代码示例如下:

now := time.Now()
year, month, day := now.Date()
today := time.Date(year, month, day, 0, 0, 0, 0, now.Location())
filter := bson.M{
	"profileID": profileId,
	"timestamp": bson.M{
		"$gte": today,
	},
}

(注意:如果你想要以UTC解释日期,使用now.UTC().Date()time.UTC作为位置参数。)

如果你想要编写一个范围查询,需要限制timestamp在两个时间戳之间,代码示例如下(这个示例限制了时间戳在今天凌晨和明天凌晨之间,即整个今天):

filter := bson.M{
	"profileID": profileId,
	"timestamp": bson.M{
		"$gte": today,
		"$lt":  today.AddDate(0, 0, 1),
	},
}
英文:

If the timestamp is always the creation date (it can't be a future timestamp), you don't really need a range (between) filter, you only need records where the creation timestamp is greater than today, 0 AM.

This is how it could look like:

now := time.Now()
year, month, day := now.Date()
today := time.Date(year, month, day, 0, 0, 0, 0, now.Location())
filter := bson.M{
	"profileID": profileId,
	"timestamp": bson.M{
		"$gte": today,
	},
}

(Note: if you want days interpreted in UTC, use now.UTC().Date() and time.UTC for the location.)

If you would want to write a range query where you need to restrict timestamp between 2 timestamps, this is how it could look like (this one restricts timestamps between today 0AM and tomorrow 0AM–so basically all day today):

filter := bson.M{
	"profileID": profileId,
	"timestamp": bson.M{
		"$gte": today,
		"$lt":  today.AddDate(0, 0, 1),
	},
}

huangapple
  • 本文由 发表于 2022年3月20日 16:39:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/71545261.html
匿名

发表评论

匿名网友

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

确定