How to construct an $or query in mgo
Asked Answered
M

2

17

I am trying to convert this JS MongoDB query into Go mgo query:

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

This is what I've got so far, but it doesn't work:

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

EDIT: It does seem to work now. Maybe I had a typo somewhere.

Mellar answered 5/12, 2014 at 19:39 Comment(1)
The syntax of the snippet looks correct. Can you show more of your code?Canorous
E
26

Here is a complete example which works fine for me (with Go 1.4, and 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)
}
Egotism answered 5/12, 2014 at 20:43 Comment(1)
Great Answer! FYI, redeclaring the type within the slice is redundant, this would suffice: err = c.Find( bson.M{ "$or": []bson.M{{"uuid":"UUID0"}, {"name": "Joe"} } } ).One(&result) Not critical, but just cleaner I think.Pash
O
1
    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

   } `

Reference https://gopkg.in/mgo.v2 Best Mongo db interface for go lang

Orton answered 7/5, 2018 at 7:44 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.