Search code examples
mongodbgomgo

query by date in mongodb


I'm able to insert an entry into MongoDB using the golang driver gopkg.in/mgo.vs and gopkg.in/mgo.vs/bson but I'm not able to pull it out. In the mongo shell, if I do

db.Items.find({ date : 1428762411980 })

it shows me the entry that I just inserted with the Go code. However, if I try to do the following to fetch it in Go, it's telling me that the record isn't found

    func fetch(w http.ResponseWriter, r *http.Request){
         var result SomeStruct
         date := r.FormValue("date")
         err := Items.Find(bson.M{"date":date}).One(&result)
         ...code omitted...

    }

   func Items() *mgo.Collection {
       return DB().C("Items")
    }

   func DB() *mgo.Database {
      return DBSession().DB("mydb")
    }

One thing I noticed was that, in the shell, the date is stored as a NumberLong

 "date" : NumberLong("1428762411980")

I'm wondering if I have to do something with the date value that I receive from the form in the fetch function before using it to query the database?

Update

Before saving the data to the db, it comes in as a json string like this

"date":1428762411980

I then decode it into a struct

type blah struct{
    Id bson.ObjectId `json:"id" bson:"_id"`
    Date int64 `json:"date" bson: "date"`

And it gets saved like this (as shown in the shell)

 "date" : NumberLong("1428762411980")

Solution

  • r.FormValue returns a string, but you need an int64. Use strconv.ParseInt. Then your query should work.

    date, err := strconv.ParseInt(r.FormValue("date"), 10, 64)
    // handle err
    err = Items.Find(bson.M{"date":date}).One(&result)