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

user2312578:

好吧,说你有很多帖子

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

当然每个帖子都有一个在特定时间创建的唯一ID。

我可以用获取时间值post.Id.Time()

但是,如何查询2015年的帖子?

我将如何对自01.01.2014-31.12.2015起的帖子进行范围查询?

我假设我需要遍历结果,检查是否post.Id.Time()介于2014年1月1日至2015年12月31日之间,以及是否将其添加到帖子切片中。

是否有使用mgo驱动程序搜索在特定范围内或特定日期发布的帖子的简单方法?

如果没有,我将接受“否”作为答案。如果有的话,我将接受并给出答案,并提供示例代码。

我在Stackoverflow上找到了这篇文章:1

但是我不知道这将如何应用于bson.ObjectId,因为它们键入的不是time.Time而是bson.ObjectId。

user2312578:

这是您的操作方式。

  • 组装fromDate和toDate。
  • 创建bson.ObjectIdbson.NewObjectIdWithTime()
  • 查询日期范围

示例:查询创建于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 {
}

注:由于ObjectId没有ISODate装配ObjectIdISODate

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章