0

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.

Community
  • 1
  • 1

2 Answers2

2

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

0

You should add a date field into the documents, over which you can query. That is the easiest option.

type Post struct {
    Id bson.ObjectId `bson:"_id"`
    date time.Time `bson:"date"`
}

Then you can write your queries over the date object.

Sundar
  • 1,691
  • 1
  • 14
  • 20