我想获取行:
{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.
答案 0 :(得分:0)
您在with open("./path/to/local/script.bash") as process_stdin:
p = subprocess.Popen(["/usr/bin/ssh", "-q", server, "--", "bash", "-s"],
stdin=process_stdin, stdout=subprocess.PIPE)
out, err = p.communicate()
之前错过了一个M{
,并且在您添加之后不要忘记添加另一个右括号"$and"
。
答案 1 :(得分: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)
}
}
我可能最终还会为mongo连接创建一个单独的包,以便我可以围绕调用编写包装函数,
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
或为您审核代码的ide。此外,mgo
是你想要使用的mongo驱动程序,如果你还没有使用它。