go - How to construct an $or query in mgo -
i trying convert js mongodb query go mgo query:
var foo = "bar"; db.collection.find({"$or": [ {uuid: foo}, {name: foo} ] });
this i've got far, doesn't work:
conditions := bson.m{"$or": []bson.m{bson.m{"uuid": name}, bson.m{"name": name}}}
edit: seem work now. maybe had typo somewhere.
here complete example works fine me (with go 1.4, , mongodb 2.6.5)
package main import ( "fmt" "log" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type person struct { num int uuid string name string } func main() { // connect database session, err := mgo.dial("localhost") if err != nil { panic(err) } defer session.close() // remove people collection if c := session.db("test").c("people") c.dropcollection() // add data err = c.insert(&person{ 1, "uuid1", "joe"}, &person{ 2, "uuid2", "jane"}, &person{ 3, "uuid3", "didier" }) if err != nil { log.fatal(err) } result := person{} err = c.find( bson.m{ "$or": []bson.m{ bson.m{"uuid":"uuid0"}, bson.m{"name": "joe"} } } ).one(&result) if err != nil { log.fatal(err) } fmt.println(result) }
Comments
Post a Comment