@ Стенни: Спасибо за подробные объяснения.Я уже видел упомянутые примеры, но они выглядят очень низкоуровневыми и не являются идиоматичными для меня.Итак, я пришел к следующему:
// Size defines the item size
type Size struct {
H int
W float64
Uom string
}
// Item defines an item
type Item struct {
OID objectid.ObjectID `bson:"_id,omitempty"` // omitempty not working
Item string
Qty int
Tags []string
Size Size
}
func main() {
// connect to MongoDB
client, err := mongo.Connect(context.Background(), "mongodb://localhost:27017", nil)
if err != nil {
log.Fatal(err)
}
db := client.Database("mongosample")
inventory := db.Collection("inventory")
// write document
itemWrite := Item{Item: "canvas", Qty: 100, Tags: []string{"cotton"}, Size: Size{H: 28, W: 35.5, Uom: "cm"}}
itemWrite.OID = objectid.New()
fmt.Printf("itemWrite = %v\n", itemWrite)
result, err := inventory.InsertOne(context.Background(), itemWrite)
if err != nil {
log.Fatal(err)
}
fmt.Printf("result = %#v\n", result)
// read documents
cursor, err := inventory.Find(
context.Background(),
bson.NewDocument(bson.EC.String("item", "canvas")),
)
if err != nil {
log.Fatal(err)
}
defer cursor.Close(context.Background())
itemRead := Item{}
for cursor.Next(context.Background()) {
err := cursor.Decode(&itemRead)
if err != nil {
log.Fatal(err)
}
fmt.Printf("itemRead = %v\n", itemRead)
}
}
У меня нет необходимости контролировать ObjectID в приложении и я хочу, чтобы драйвер или база данных генерировали ID по требованию.Проблема здесь: я не смог найти способ опустить идентификатор.Это bson:"_id,omitempty"
не работает.Это приводит к OID со всем установленным в ноль 'ObjectID ("000000000000000000000000")'.Может быть общая проблема, потому что ObjectID является массивом, а не срезом: тип ObjectID [12] байт