使用golang和mgo,我如何在MongoDB中搜索一系列值?
问题描述:
我通过 mgo主页上的示例工作,但我正在努力寻找一种方法来查询值的范围。该行: searchResults,searchErr = SearchReading(bson.M {k:key,t:{$ gte:start,$ lte:end}},limit )
失败: line67:语法错误:意外的$
line67:复合字面值中缺少的类型
I worked through the example on the mgo homepage, but I'm struggling to find a way to query a range of values. The line:searchResults, searchErr = SearchReading(bson.M{"k": key, "t": { $gte: start, $lte: end } }, limit)
fails with:line67: syntax error: unexpected $
line67: missing type in composite literal
我忽略了非必要的代码位...
I left out the non-essential bits of code...
type Reading struct {
K string "k"
T int64 "t"
V float64 "v"
}
func SearchReading(q interface{}, limit int) (searchResults []Reading, searchErr string) {
searchErr = ""
searchResults = []Reading{}
query := func(c *mgo.Collection) error {
fn := c.Find(q).Limit(limit).All(&searchResults)
if limit < 0 {
fn = c.Find(q).All(&searchResults)
}
return fn
}
search := func() error {
return withCollection("reading", query)
}
err := search()
if err != nil {
searchErr = "Database Error"
}
return
}
func GetReadingsForKey(key string, start int64, end int64, limit int) (searchResults []Reading, searchErr string) {
searchResults, searchErr = SearchReading(bson.M{"k": key, "t": { $gte: start, $lte: end } }, limit)
return
}
答
行:
The line:
searchResults, searchErr = SearchReading(bson.M{"k": key, "t": { $gte: start, $lte: end } }, limit)
需要更改为:
needs to change to:
searchResults, searchErr = SearchReading(bson.M{"k": key, "t": bson.M{"$gte": start, "$lte": end}}, limit)