0

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")
BrainLikeADullPencil
  • 11,313
  • 24
  • 78
  • 134
  • I think In your documents date save in `unix time stamp` check this http://stackoverflow.com/questions/11996693/golang-mgo-how-can-i-ask-mongodb-to-use-current-time-in-a-field – Neo-coder Apr 11 '15 at 16:21
  • I'm sorry, I don't fully get your point. Before saving the record, I decode it to a field like this `Date int64 `json:"date" bson: "date"`` What would you recommend I do? – BrainLikeADullPencil Apr 11 '15 at 16:50
  • Should I create another field on the struct with a different type and convert the unix time stamp to another type to use for storage. If so, what and how? – BrainLikeADullPencil Apr 11 '15 at 16:59

1 Answers1

1

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)
guregu
  • 176
  • 5