2016-02-12 57 views
7

我需要使用ObjectIdHex來獲取值並進行更新並查看結果。我使用的MongoDB和預期如何在golang和mongodb中使用id查找

golang.But下面的代碼不起作用
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不能工作 –

回答

9

應該_idId

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

我得到相同的結果和錯誤.. –

+2

大衛Budworth是正確的。不要丟棄收集,或不要硬編碼ID。 –

+0

這個答案是錯誤的。您可以使用['Collection.FindId()'](https://godoc.org/gopkg.in/mgo.v2#Collection.FindId),然後只傳遞id值,或者使用['Collection.Find ()'](https://godoc.org/gopkg.in/mgo.v2#Collection.Find),然後你必須用字段名稱指定一個值。看到這個答案:[通過ID查找與mgo](https://stackoverflow.com/questions/41244024/find-by-id-with-mgo/41244172#41244172)。 – icza