golang으로 데이터를 다루다 mongoDB의 id 값 다루는 과정 중 정리해두면 좋을 것 같아 작성하게 되었습니다.
Collection에 데이터를 생성하면 ObjectId가 자동으로 함께 생성된다.
type Person struct {
Name string `bson:"name"`
Age int `bson:"age"`
Pnum string `bson:"pnum,omitempty"`
}
func ObjectIDFromHex(s string) (ObjectID, error)
해당 함수를 사용하면 string 값을 받아 ObjectID로 변환할 수 있다.var person Person
pId, err := primitive.ObjectIDFromHex("63a95f1a80eab6d85dca3130")
err = coll.FindOne(context.TODO(), bson.M{"_id": pId}).Decode(&person)
fmt.Printf("%v\n", person)
var person Person
pId, err := primitive.ObjectIDFromHex("63a95f1a80eab6d85dca3130")
func(pId primitive.ObjectID) {
err = coll.FindOne(context.TODO(), bson.M{"_id": pId}).Decode(&person)
fmt.Printf("%v\n", person)
}(pId)
func NewObjectID() ObjectID
newId := primitive.NewObjectID()
fmt.Println(newId)
func NewObjectIDFromTimestamp(timestamp time.Time) ObjectID
tempTime := time.Now()
newId := primitive.NewObjectIDFromTimestamp(tempTime)
fmt.Println(newId)