Go學習:Mongo客戶端報錯cannot transform type bson.D to a BSON Document: WriteArray can only write a Array

網上有些文章給的示例直接傳bson.D,可能是客戶端版本問題,在mongo-go-driver@v2.0.0上Find方法要求傳入type M map[string]interface{},直接傳bson.D會報如下錯誤:

“cannot transform type bson.D to a BSON Document: WriteArray can only write a Array while positioned on a Element or Value but is positioned on a TopLevel”

//報錯:cannot transform type bson.D to a BSON Document: WriteArray can only write a Array while positioned on a Element or Value but is positioned on a TopLevel
cur, err := collection.Find(ctx, bson.D{{"type", "電視劇"}})

//正確
cur, err := collection.Find(ctx, bson.D{{"type", "電視劇"}}.Map())

//正確
cur, err := collection.Find(ctx, bson.M{"type":"電視劇"})

詳細的示例請參見《Go學習:[email protected]模塊遍歷查詢Mongodb表(Find)》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章