【问题标题】:How to construct an $or query in mgo如何在 mgo 中构造 $or 查询
【发布时间】:2015-02-04 01:36:29
【问题描述】:

我正在尝试将此 JS MongoDB 查询转换为 Go mgo 查询:

var foo = "bar";
db.collection.find({"$or": [ {uuid: foo}, {name: foo} ] });

这是我到目前为止所得到的,但它不起作用:

conditions := bson.M{"$or": []bson.M{bson.M{"uuid": name}, bson.M{"name": name}}}

编辑:它现在似乎确实有效。也许我在某个地方打错了。

【问题讨论】:

  • sn-p 的语法看起来是正确的。你能展示更多你的代码吗?

标签: go mgo


【解决方案1】:

这是一个对我来说很好的完整示例(使用 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 to the database
    session, err := mgo.Dial("localhost")
    if err != nil {
            panic(err)
    }
    defer session.Close()

    // Remove people collection if any
    c := session.DB("test").C("people")
    c.DropCollection()

    // Add some 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)
}

【讨论】:

  • 很好的答案!仅供参考,在切片中重新声明类型是多余的,这就足够了:err = c.Find( bson.M{ "$or": []bson.M{{"uuid":"UUID0"}, {"name": "Joe"} } } ).One(&result) 不重要,但我认为更简洁。
【解决方案2】:
    package main

    import (
     "fmt"
        "gopkg.in/mgo.v2"
        "gopkg.in/mgo.v2/bson"

    )
func GetAll()[]interface{}{
           //Data Base Instance
        session, err := mgo.Dial("localhost")
        c := session.DB("yourDbName").C("YourCollectionName")
            foo := "bar"
            orQuery := []bson.M{}
            uidFindQuery := bson.M{uuid: foo}
            nameFindQuery := bson.M{name: foo}
            orQuery = append(orQuery, uidFindQuery, nameFindQuery)
             result := []interface{}{}
            err := c.Find(bson.M{"$or":orQuery}).All(&result);
           fmt.Println("error", err)
           fmt.Println("Your expected Data",result)
           return result

   } `

参考 https://gopkg.in/mgo.v2 go lang 的最佳 Mongo db 接口

【讨论】:

    猜你喜欢
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    相关资源
    最近更新 更多