Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
like image 470
Jaco Briers Avatar asked Oct 31 '12 12:10

Jaco Briers


People also ask

How do I search in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.

Does MongoDB use Golang?

Go is one of the newest languages to get an official MongoDB driver, and the combination of Go's compiled performance and lightweight, data-friendly syntax makes Go with MongoDB a fantastic match for building data-driven applications.

What is BSON M?

M : An unordered representation of a BSON document (map) A : An ordered representation of a BSON array. E : A single element inside a D type.


1 Answers

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)
like image 100
Jaco Briers Avatar answered Oct 16 '22 19:10

Jaco Briers