如何在Golang和MongoDB中通过ID进行查找

25

我需要使用 ObjectIdHex 获取值,进行更新并查看结果。我正在使用 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) 对我不起作用,并给出以下输出

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)

我该如何解决这个问题?我需要使用oid获取值并进行更新,那我该怎么做呢?


4
你正在删除记录,重新插入它们,然后使用硬编码的ID。当你插入一条记录时,它会被分配一个随机的ID,每次运行都会不同。你的硬编码ID无法起作用。 - David Budworth
3个回答

35

您可以使用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)

3
这应该是最新的被接受的答案。感谢您提供这个答案。 - Carlo Nyte

20

应该使用_id而不是Id

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

2
David Budworth是正确的。不要删除集合,也不要硬编码ID。 - Alex Blex
2
这个答案是错误的。你要么使用 Collection.FindId() 然后只传递 id 值,或者你使用 Collection.Find() 然后你必须指定一个带有字段名称的值。参见此答案:Find by id with mgo - icza
2
这是一个错误的答案,因为ObjectIdHex()的返回类型是bson.ObjectId,但实际上您需要将primitive.ObjectID类型传递给Mongo过滤器。 - Amin Shojaei

2
一些我使用的示例代码。
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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接