按日期范围过滤mongoDB

我正在尝试使用 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")

}


喵喔喔
浏览 167回答 1
1回答

潇湘沐

如果时间戳始终是创建日期(不能是未来的时间戳),则您实际上不需要范围(介于)过滤器,您只需要创建时间戳大于今天上午 0 点的记录。这就是它的样子: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在 2 个时间戳之间进行限制,这就是它的样子(这个限制了今天早上 0 点到明天早上 0 点之间的时间戳——所以基本上今天一整天):filter := bson.M{    "profileID": profileId,    "timestamp": bson.M{        "$gte": today,        "$lt":  today.AddDate(0, 0, 1),    },}
打开App,查看更多内容
随时随地看视频慕课网APP