2017-09-13 104 views
0

我想在那裏行:

{repair field has "ac" OR {repair is "tv" and phone field in range 1091-1100}} 

我想下面的查詢:

type M map[string]interface{} 
conditions := M{"name": M{"$regex": "me"}, 
    "$or": []M{M{"repair": M{"$eq": "ac"}}, 
"$and": []M{M{"repair": M{"$eq": "tv"}}, M{"phone": M{"$gte": 1091, "$lte": 1100}}}}} 
    fmt.Println(conditions) 
    err = c.Find(conditions).Sort("phone").Limit(20).All(&j) 

但是,我得到一個編譯錯誤:

index must be non-negative integer constant 
cannot use []M literal (type []M) as type M in array or slice literal. 
+1

你用什麼庫爲MongoDB? –

+0

'j'的類型是什麼? – Adrian

+0

我正在使用包gopkg.in/mgo.v2和j是var j [] M –

回答

0

你錯過了一個M{"$and"之前和之後補充說,不要」 t忘記添加另一個右大括號}

the goodthe bad作比較。

+0

非常感謝mkopriva。我剛剛開始在Go(1month) –

0

我不知道你使用的是什麼驅動程序,但我可能會做這樣的事情..

package main 

import (
    "log" 
    "time" 

    mgo "gopkg.in/mgo.v2" 
    "gopkg.in/mgo.v2/bson" 
) 

const (
    databaseString = "" 
) 

var db DataStore 

type DataStore struct { 
    Session *mgo.Session 
} 


// database 
func (ds *DataStore) ConnectToDB() { 

    mongoDBDialInfo := &mgo.DialInfo{ 
     Addrs: []string{"localhost:27017"}, 
     Timeout: 1 * time.Hour, 
    } 

    sess, err := mgo.DialWithInfo(mongoDBDialInfo) 
    if err != nil { 
     sess.Refresh() 
     panic(err) 
    } 
    sess.SetMode(mgo.Monotonic, true) 
    db.Session = sess 
} 

// J is the expected mongo return object 
type J struct { 
    ID bson.ObjectId `bson:"_id,omitempty" json:"_id"` 
    // example data below 
    Status string `bson:"status" json:"status"` 
} 

func init() { 
    db.ConnectToDB() 
} 

func main() { 
    colectionString := "" 
    // probably best if this was a mapped mgo struct see above 
    // var j bson.M 

    var j J 

    // your orignal code 
    // I don't know why you are using $eq couldn't you just do bson.M{"repair":"ac"}, and bson.M{"repair":"tv"} 
    conditions := bson.M{"name": bson.M{"$regex": "me"}, 
     "$or": []bson.M{ 
      bson.M{"repair": bson.M{"$eq": "ac"}}, 
     }, 
     "$and": []bson.M{ 
      bson.M{"repair": bson.M{"$eq": "tv"}}, 
      bson.M{"phone": bson.M{"$gte": 1091, "$lte": 1100}}, 
     }} 

    err := db.Session.DB(databaseString).C(colectionString).Find(conditions).Sort("phone").Limit(20).All(&j) 
    if err != nil { 
     log.Fatal(err) 
    } 
} 

我可能會也結束了蒙戈連接東西創建一個單獨的包,這樣我可以寫呼叫周圍的包裝函數,

func FindItem(db *mgo.Session, id string) (data, error) { 
    defer sess.Close() 
    var res data //some data type struct 
    err := sess.DB("my db").C("my collection").Find(bson.M{"user": someID}).One(&data) 
    return data, err 
} 

那麼我可以做這樣的事情,這允許併發

res, err := packagemain.FindItem(sess.Copy(), someID) 

和你原來的代碼你在哪裏丟失},。我建議你使用go vet或者代碼爲你做代碼。此外,mgo是mongo驅動程序,如果您尚未使用,可能是您想要使用的驅動程序。

+0

編碼,謝謝reticentroot。這比我的要乾淨得多,並且用以下代替eq: –