duanreng3439 2016-08-17 14:04
浏览 93

mongodb golang按日期限制结果

I have a mongodb collection that I am trying to limit the result set, but the data was created by someone else and the date format appears to be stored as "2016-05-12 00:00:00.000Z". I am unsure how to format my find query to limit this type of date. I have been successful with other types of date formats, but not this one. Has anyone else encountered this issue?

myCollection {
  "_id" : {
    "$oid" : bson.ObjectId
  },
  "createdDate" : {
    "$date" : Date
} 

This is what I have attempted.

toDate := time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.UTC)
fromDate := toDate.AddDate(0, 0, -1)

collectionResult := collectionRecords.Find(bson.M{"retailer": result.Id, "createdAt": bson.M{"$gte": fromDate}})

Ultimately, I would like to limit to one day and was attempting to do the following:

collectionResult := collectionRecords.Find(bson.M{"retailer": result.Id, "createdAt": bson.M{"$gte": fromDate, "$lt": toDate}})
collectionResult.All(&collectionData)
collectionCount, _ := collectionResult.Count()
fmt.Println("Count: ", collectionCount)

it always returns 0. Like I stated above I have been successful with UTC dates, but this one seems to trouble me.

  • 写回答

2条回答 默认 最新

  • dongxi4335 2016-08-17 14:19
    关注

    If I understand the question, you're looking how to create a UTC timestamp 24 hours into the past where hours have been truncated?

    You can try filtering on these dates:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        today := time.Now().Truncate(24*time.Hour).UTC()
        yesterday := today.Add(-24*time.Hour)
        fmt.Println(today)
        fmt.Println(yesterday)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器