Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

go

mgo

Hi I have a collection named "my_sales" having fields product_name, price, sale_date.

My doc looks like

{
    "_id" : ObjectId("5458b6ee09d76eb7326df3a4"),
    "product_name" : product1,
    "price" : 200,
    "sale_date" : ISODate("2014-11-04T11:22:19.589Z")
}
{
    "_id" : ObjectId("5458b6ee09d76eb7326df3a4"),
    "product_name" : product1,
    "price" : 200,
    "sale_date" : ISODate("2014-11-04T11:22:19.589Z")
}
{
    "_id" : ObjectId("5458b6ee09d76eb7326df3a4"),
    "product_name" : product1,
    "price" : 200,
    "sale_date" : ISODate("2014-11-04T11:22:19.589Z")
}
{
    "_id" : ObjectId("5458b6ee09d76eb7326df3a4"),
    "product_name" : product1,
    "price" : 200,
    "sale_date" : ISODate("2014-11-05T11:22:19.589Z")
}

I tried in mongo shell like this

 db.my_sales.find({ sale_date: { $gt: ISODate("2014-11-04"), $lt: new ISODate("2014-11-05") });

It giving the correct result. Now I need to query same thing using golang I tried like this

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

Its giving null result please help

like image 425
manigandand Avatar asked Nov 06 '14 07:11

manigandand


People also ask

Which method is used to query data from MongoDB collection?

The find() Method To query data from MongoDB collection, you need to use MongoDB's find() method.

How does MongoDB select date?

the Date() Method in MongoDB In MongoDB shell or mongosh, the Date() method returns the current date as a string. The new Date() function returns a Date object with the current date. The ISODate helper is wrapped around the Date object by mongosh, and the ISODate is in UTC (Universal Time).


2 Answers

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)
like image 101
icchanobot Avatar answered Oct 12 '22 12:10

icchanobot


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.

like image 25
Vui Teenmax Avatar answered Oct 12 '22 12:10

Vui Teenmax