Using golang and mgo, how do I search for a range of values in MongoDB?

孤人 提交于 2019-12-07 02:11:48

问题


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
}

回答1:


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)


来源:https://stackoverflow.com/questions/13158335/using-golang-and-mgo-how-do-i-search-for-a-range-of-values-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!