How can I query MongoDB with date range using mgo and Go?

I have new way to query date range:

// convert to date
fromTime := time.Unix(1509358405981/1000, 0)     

// Convert date to ObjectID with time    
fromObjectBson := bson.NewObjectIdWithTime(fromTime)

// condition     
bson.M{"_id":bson.M{"$gt": fromObjectBson}} 

This will speedup your query.


mgo supports time.Time for BSON dates.

So if your struct looks like this:

type Sale struct {
    ProductName string    `bson:"product_name"`
    Price       int       `bson:"price"`
    SaleDate    time.Time `bson:"sale_date"`
}

Then you can query it like this:

fromDate := time.Date(2014, time.November, 4, 0, 0, 0, 0, time.UTC)
toDate := time.Date(2014, time.November, 5, 0, 0, 0, 0, time.UTC)

var sales_his []Sale
err = c.Find(
    bson.M{
        "sale_date": bson.M{
            "$gt": fromDate,
            "$lt": toDate,
        },
    }).All(&sales_his)

Tags:

Mongodb

Go

Mgo