使用golang和mgo,如何在MongoDB中搜索一系列值?

时间:2012-10-31 12:48:12

标签: mongodb go mongodb-query mgo

我在mgo homepage上完成了示例,但我很难找到一种方法来查询一系列值。这一行:
searchResults, searchErr = SearchReading(bson.M{"k": key, "t": { $gte: start, $lte: end } }, limit)
失败的是:
line67: syntax error: unexpected $
line67: missing type in composite literal

我遗漏了非必要的代码......

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 个答案:

答案 0 :(得分:12)

该行:

searchResults, searchErr = SearchReading(bson.M{"k": key, "t": { $gte: start, $lte: end } }, limit)

需要更改为:

searchResults, searchErr = SearchReading(bson.M{"k": key, "t": bson.M{"$gte": start, "$lte": end}}, limit)