duan0504 2015-07-19 14:22
浏览 67
已采纳

mgo:查询ObjectId以获取时间值范围

Ok, say you have a number of posts

type Post struct {
    Id bson.ObjectId `bson:"_id,omitempty"`
}

and each post of course has a unique id that was created at a certain time.

I can get the time value with post.Id.Time().

However how do I query for posts from let's say the year 2015?

And how would I do a range query for posts since 01.01.2014-31.12.2015?

I would assume that I need to iterate over results, check if post.Id.Time() is between 01.01.2014 and 31.12.2015 and if it is add it to a posts slice.

Is there a less complicated way to search for posts made between certain ranges or at a certain date using the mgo driver?

If there isn't I will accept No as an answer. If there is I will accept and answer that shows how, with code example.

I have found this post on Stackoverflow:1

However I don't know how this would apply to a bson.ObjectId since they type isn't time.Time but bson.ObjectId.

  • 写回答

2条回答 默认 最新

  • dpoppu4300 2015-07-21 14:25
    关注

    Here's how you do it.

    • Assemble fromDate and toDate.
    • Create bson.ObjectId with bson.NewObjectIdWithTime()
    • Query for date range

    Example: Query for posts created 2015

    year := 2015
    fromDate := time.Date(year, time.January, 1, 0, 0, 0, 0, time.UTC)
    toDate := time.Date(year+1, time.January, 1, 0, 0, 0, 0, time.UTC)
    fromId := bson.NewObjectIdWithTime(fromDate)
    toId := bson.NewObjectIdWithTime(toDate)
    posts := []*Post{}
    if e := cPost.Find(bson.M{"_id": bson.M{"$gte": fromId, "$lt": toId}}).All(&posts); e != nil {
    }
    

    note: Because ObjectId isn't ISODate assemble ObjectId from ISODate

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教