How to find by id in golang and mongodb

huangapple go评论114阅读模式
英文:

How to find by id in golang and mongodb

问题

我需要使用ObjectIdHex获取值,并进行更新操作,然后查看结果。我正在使用mongodb和golang。但是以下代码并没有按预期工作:

  1. package main
  2. import (
  3. "fmt"
  4. "gopkg.in/mgo.v2"
  5. "gopkg.in/mgo.v2/bson"
  6. )
  7. type Person struct {
  8. Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
  9. Name string
  10. Phone string
  11. }
  12. func checkError(err error) {
  13. if err != nil {
  14. panic(err)
  15. }
  16. }
  17. const (
  18. DB_NAME = "gotest"
  19. DB_COLLECTION = "pepole_new1"
  20. )
  21. func main() {
  22. session, err := mgo.Dial("localhost")
  23. checkError(err)
  24. defer session.Close()
  25. session.SetMode(mgo.Monotonic, true)
  26. c := session.DB(DB_NAME).C(DB_COLLECTION)
  27. err = c.DropCollection()
  28. checkError(err)
  29. ale := Person{Name: "Ale", Phone: "555-5555"}
  30. cla := Person{Name: "Cla", Phone: "555-1234-2222"}
  31. kasaun := Person{Name: "kasaun", Phone: "533-12554-2222"}
  32. chamila := Person{Name: "chamila", Phone: "533-545-6784"}
  33. fmt.Println("Inserting")
  34. err = c.Insert(&ale, &cla, &kasaun, &chamila)
  35. checkError(err)
  36. fmt.Println("findbyID")
  37. var resultsID []Person
  38. err = c.FindId(bson.M{"Id": bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")}).One(&resultsID)
  39. checkError(err)
  40. if err != nil {
  41. panic(err)
  42. }
  43. fmt.Println("Phone:", resultsID)
  44. fmt.Println("Queryingall")
  45. var results []Person
  46. err = c.Find(nil).All(&results)
  47. if err != nil {
  48. panic(err)
  49. }
  50. fmt.Println("Results All: ", results)
  51. }

FindId(bson.M{"Id": bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")}).One(&resultsID)对我来说不起作用,并给出以下输出:

  1. Inserting
  2. Queryingall
  3. 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}]
  4. findbyID
  5. panic: not found
  6. goroutine 1 [running]:
  7. main.checkError(0x7f33d524b000, 0xc8200689b0)

你如何解决这个问题?我需要使用对象ID获取值并进行更新,你能告诉我如何做到这一点吗?

英文:

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

  1. package main
  2. import (
  3. "fmt"
  4. "gopkg.in/mgo.v2"
  5. "gopkg.in/mgo.v2/bson"
  6. )
  7. type Person struct {
  8. Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
  9. Name string
  10. Phone string
  11. }
  12. func checkError(err error) {
  13. if err != nil {
  14. panic(err)
  15. }
  16. }
  17. const (
  18. DB_NAME = "gotest"
  19. DB_COLLECTION = "pepole_new1"
  20. )
  21. func main() {
  22. session, err := mgo.Dial("localhost")
  23. checkError(err)
  24. defer session.Close()
  25. session.SetMode(mgo.Monotonic, true)
  26. c := session.DB(DB_NAME).C(DB_COLLECTION)
  27. err = c.DropCollection()
  28. checkError(err)
  29. ale := Person{Name:"Ale", Phone:"555-5555"}
  30. cla := Person{Name:"Cla", Phone:"555-1234-2222"}
  31. kasaun := Person{Name:"kasaun", Phone:"533-12554-2222"}
  32. chamila := Person{Name:"chamila", Phone:"533-545-6784"}
  33. fmt.Println("Inserting")
  34. err = c.Insert(&ale, &cla, &kasaun, &chamila)
  35. checkError(err)
  36. fmt.Println("findbyID")
  37. var resultsID []Person
  38. //err = c.FindId(bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")).One(&resultsID)
  39. err = c.FindId(bson.M{"Id": bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")}).One(&resultsID)
  40. checkError(err)
  41. if err != nil {
  42. panic(err)
  43. }
  44. fmt.Println("Phone:", resultsID)
  45. fmt.Println("Queryingall")
  46. var results []Person
  47. err = c.Find(nil).All(&results)
  48. if err != nil {
  49. panic(err)
  50. }
  51. fmt.Println("Results All: ", results)
  52. }

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

  1. Inserting
  2. Queryingall
  3. 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}]
  4. findbyID
  5. panic: not found
  6. goroutine 1 [running]:
  7. 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

答案1

得分: 34

你可以使用Golang官方驱动程序来执行相同的操作,代码如下:

  1. // 将id字符串转换为ObjectId
  2. objectId, err := primitive.ObjectIDFromHex("5b9223c86486b341ea76910c")
  3. if err != nil {
  4. log.Println("无效的id")
  5. }
  6. // 查询
  7. result := client.Database(database).Collection("user").FindOne(context.Background(), bson.M{"_id": objectId})
  8. user := model.User{}
  9. result.Decode(&user)

请注意,这是一个示例代码,你需要根据你的实际情况进行适当的修改。

英文:

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

  1. // convert id string to ObjectId
  2. objectId, err := primitive.ObjectIDFromHex("5b9223c86486b341ea76910c")
  3. if err != nil{
  4. log.Println("Invalid id")
  5. }
  6. // find
  7. result:= client.Database(database).Collection("user").FindOne(context.Background(), bson.M{"_id": objectId})
  8. user := model.User{}
  9. result.Decode(user)

答案2

得分: 19

应该是 _id 而不是 Id

  1. c.FindId(bson.M{"_id": bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")})
英文:

It should be _id not Id:

  1. c.FindId(bson.M{"_id": bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")})

答案3

得分: 2

一些我使用的示例代码。

  1. func (model *SomeModel) FindId(id string) error {
  2. db, ctx, client := Drivers.MongoCollection("collection")
  3. defer client.Disconnect(ctx)
  4. objID, err := primitive.ObjectIDFromHex(id)
  5. if err != nil {
  6. return err
  7. }
  8. filter := bson.M{"_id": bson.M{"$eq": objID}}
  9. if err := db.FindOne(ctx, filter).Decode(&model); err != nil {
  10. //fmt.Println(err)
  11. return err
  12. }
  13. fmt.Println(model)
  14. return nil
  15. }

请注意,这只是示例代码,具体的实现可能会根据你的需求而有所不同。

英文:

Some sample code that i use.

  1. func (model *SomeModel) FindId(id string) error {
  2. db, ctx, client := Drivers.MongoCollection("collection")
  3. defer client.Disconnect(ctx)
  4. objID, err := primitive.ObjectIDFromHex(id)
  5. if err != nil {
  6. return err
  7. }
  8. filter := bson.M{"_id": bson.M{"$eq": objID}}
  9. if err := db.FindOne(ctx, filter).Decode(&model); err != nil {
  10. //fmt.Println(err)
  11. return err
  12. }
  13. fmt.Println(model)
  14. return nil
  15. }

huangapple
  • 本文由 发表于 2016年2月12日 22:18:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/35364816.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定