Search code examples
gomgo

mgo: Query ObjectId for range of time values


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.


Solution

  • 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