我正在嘗試使用 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")}
1 回答

瀟湘沐
TA貢獻1816條經驗 獲得超6個贊
如果時間戳始終是創建日期(不能是未來的時間戳),則您實際上不需要范圍(介于)過濾器,您只需要創建時間戳大于今天上午 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),
},
}
- 1 回答
- 0 關注
- 209 瀏覽
添加回答
舉報
0/150
提交
取消