简体   繁体   English

如何在golang和mongodb中通过id查找

[英]How to find by id in golang and mongodb

I need get values using ObjectIdHex and do update and also view the result.我需要使用 ObjectIdHex 获取值并进行更新并查看结果。 I'm using mongodb and golang.But following code doesn't work as expected我正在使用 mongodb 和 golang。但是下面的代码没有按预期工作

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 FindId(bson.M{"Id": bson.ObjectIdHex("56bdd27ecfa93bfe3d35047d")}).One(&resultsID)对我不起作用并给了我以下输出

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我需要使用 oid 获取价值并进行更新,我该怎么做

Use can do the same with Golang official driver as follows:使用 Golang 官方驱动也可以,如下:

// 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)

它应该是_id而不是Id

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

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
}

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

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