小编典典

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

go

我在mgo主页上浏览了该示例,但是我一直在努力寻找一种查询一系列值的方法。该行:
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
}

阅读 226

收藏
2020-07-02

共1个答案

小编典典

该行:

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)
2020-07-02