25

I need get values using ObjectIdHex and do update and also view the result. I'm using mongodb and golang.But following code doesn't work as expected

package main

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

type Person struct {
    Id      bson.ObjectId `json:"id" bson:"_id,omitempty"`
    Name  string
    Phone string
}

func checkError(err error) {
    if err != nil {
        panic(err)
    }
}

const (
    DB_NAME       = "gotest"
    DB_COLLECTION = "pepole_new1"
)

func main() {
    session, err := mgo.Dial("localhost")
    checkError(err)
    defer session.Close()

    session.SetMode(mgo.Monotonic, true)

    c := session.DB(DB_NAME).C(DB_COLLECTION)
    err = c.DropCollection()
    checkError(err)

    ale := Person{Name:"Ale", Phone:"555-5555"}
    cla := Person{Name:"Cla", Phone:"555-1234-2222"}
    kasaun := Person{Name:"kasaun", Phone:"533-12554-2222"}
    chamila := Person{Name:"chamila", Phone:"533-545-6784"}

    fmt.Println("Inserting")
    err = c.Insert(&ale, &cla, &kasaun, &chamila)
    checkError(err)

    fmt.Println("findbyID")
    var resultsID []Person
    //err = c.FindId(bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")).One(&resultsID)
    err = c.FindId(bson.M{"Id": bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")}).One(&resultsID)
    checkError(err)
    if err != nil {
        panic(err)
    }
    fmt.Println("Phone:", resultsID)



    fmt.Println("Queryingall")
    var results []Person
    err = c.Find(nil).All(&results)

    if err != nil {
        panic(err)
    }
    fmt.Println("Results All: ", results)


}

FindId(bson.M{"Id": bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")}).One(&resultsID) didn't work for me and giving me following output

Inserting
Queryingall
Results All:  [{ObjectIdHex("56bddee2cfa93bfe3d3504a1") Ale 555-5555} {ObjectIdHex("56bddee2cfa93bfe3d3504a2") Cla 555-1234-2222} {ObjectIdHex("56bddee2cfa93bfe3d3504a3") kasaun 533-12554-2222} {ObjectIdHex("56bddee2cfa93bfe3d3504a4") chamila 533-545-6784}]
findbyID
panic: not found

goroutine 1 [running]:
main.checkError(0x7f33d524b000, 0xc8200689b0)

How can i fix this problem? i need get value using oid and do update also how can i do that

TheHippo
  • 61,720
  • 15
  • 75
  • 100
Nuwan Indika
  • 901
  • 4
  • 14
  • 27
  • 4
    you are deleting the records, re-inserting them then using a hard coded id. When you insert a record, it get's a random id assigned to it. It will be different every run. Your hardcoded id can't work – David Budworth Feb 12 '16 at 15:27

3 Answers3

34

Use can do the same with Golang official driver as follows:

// convert id string to ObjectId
objectId, err := primitive.ObjectIDFromHex("5b9223c86486b341ea76910c")
if err != nil{
    log.Println("Invalid id")
}

// find
result:= client.Database(database).Collection("user").FindOne(context.Background(), bson.M{"_id": objectId})
user := model.User{}
result.Decode(user)
Amin Shojaei
  • 5,451
  • 2
  • 38
  • 46
Karthikeyan
  • 2,634
  • 5
  • 30
  • 51
20

It should be _id not Id:

c.FindId(bson.M{"_id": bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")})
Alex Blex
  • 34,704
  • 7
  • 48
  • 75
  • 2
    David Budworth is right. Don't drop collection, or don't hardcode ids. – Alex Blex Feb 12 '16 at 15:31
  • 2
    This answer is wrong. You either use [`Collection.FindId()`](https://godoc.org/gopkg.in/mgo.v2#Collection.FindId) and then you pass only the id value, or you use [`Collection.Find()`](https://godoc.org/gopkg.in/mgo.v2#Collection.Find) and then you have to specify a value with the field name too. See this answer: [Find by id with mgo](https://stackoverflow.com/questions/41244024/find-by-id-with-mgo/41244172#41244172). – icza Dec 08 '17 at 11:09
  • 2
    This is a wrong answer, Because the returned type of `ObjectIdHex()` is `bson.ObjectId`, but you actually need to pass `primitive.ObjectID` type to mongo filter. – Amin Shojaei Sep 02 '20 at 07:49
2

Some sample code that i use.

func (model *SomeModel) FindId(id string) error {
    db, ctx, client := Drivers.MongoCollection("collection")
    defer client.Disconnect(ctx)

    objID, err := primitive.ObjectIDFromHex(id)

    if err != nil {
        return err
    }

    filter := bson.M{"_id": bson.M{"$eq": objID}}


    if err := db.FindOne(ctx, filter).Decode(&model); err != nil {
        //fmt.Println(err)
        return err
    }

    fmt.Println(model)
    return nil
}
Shadx
  • 21
  • 2