英文:
query by date in mongodb
问题
我能够使用golang驱动程序gopkg.in/mgo.vs
和gopkg.in/mgo.vs/bson
将条目插入到MongoDB中,但我无法将其取出。在mongo shell中,如果我执行以下操作:
db.Items.find({ date : 1428762411980 })
它会显示我刚刚使用Go代码插入的条目。然而,如果我尝试在Go中执行以下操作来获取它,它告诉我找不到记录:
func fetch(w http.ResponseWriter, r *http.Request){
var result SomeStruct
date := r.FormValue("date")
err := Items.Find(bson.M{"date":date}).One(&result)
...省略的代码...
}
func Items() *mgo.Collection {
return DB().C("Items")
}
func DB() *mgo.Database {
return DBSession().DB("mydb")
}
我注意到的一件事是,在shell中,日期存储为NumberLong
"date" : NumberLong("1428762411980")
我想知道在使用fetch
函数中从表单接收到的日期值用于查询数据库之前,是否需要对其进行某些处理?
更新
在将数据保存到数据库之前,它以json字符串的形式出现,如下所示:
"date":1428762411980
然后我将其解码为一个结构体:
type blah struct{
Id bson.ObjectId `json:"id" bson:"_id"`
Date int64 `json:"date" bson:"date"`
}
并且它以以下方式保存(如shell中所示):
"date" : NumberLong("1428762411980")
英文:
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")
答案1
得分: 1
r.FormValue
返回一个字符串,但你需要一个 int64 类型的值。可以使用 strconv.ParseInt 进行转换。然后你的查询应该可以工作了。
date, err := strconv.ParseInt(r.FormValue("date"), 10, 64)
// 处理错误
err = Items.Find(bson.M{"date": date}).One(&result)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论