MongoDB在golang中查找$ or和$ and组合的查询

I want to get rows where:

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

I am trying the following query:

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)

However, I am getting a compile error:

index must be non-negative integer constant
cannot use []M literal (type []M) as type M in array or slice literal.
dongtao9095
dongtao9095 我正在使用gopkg.in/mgo.v2软件包,并且j是varj[]M
大约 3 年之前 回复
dqask02082
dqask02082 j的类型是什么?
大约 3 年之前 回复
douhuai4155
douhuai4155 您为mongodb使用什么库?
大约 3 年之前 回复

2个回答



您在“ $ and” </ code>之前和之后缺少一个 M {</ code> 您添加的别忘了添加另一个右括号} </ code>。</ p>

进行比较。 </ p>
</ div>

展开原文

原文

You're missing one M{ before "$and" and after you add that don't forget to add another closing brace }.

the good and the bad for comparison.

duangai1941
duangai1941 非常感谢您。 我刚开始用Go编码(1个月)
大约 3 年之前 回复

I don't know what driver your using, but I would probably do something like this..

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)
    }
}

I would probably also end up creating a separate package for the mongo connection stuff so that I can write wrapper functions around calls,

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
}

then I'd be able to do things like this, which allow for concurrency

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

and your original code your you where missing } and ,. I suggest you use go vet or an ide which vets the code for you. Also, mgo is the mongo driver you probably what you want to be using if you're not using it already.

dongxu3029
dongxu3029 谢谢reticentroot。 这比我的清洁得多,也用以下方法替换了eq:
大约 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐