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)》

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