繁体   English   中英

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

[英]MongoDB find query with combination of $or and $and in golang

我想在以下位置获取行:

{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.

"$and"之前和之后,您会丢失一个M{ ,不要忘记添加另一个右括号}

好的坏的比较。

我不知道您使用的是什么驱动程序,但是我可能会做这样的事情。

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驱动程序,如果您尚未使用它,可能是您想要使用的驱动程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM