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

发布了51 篇原创文章 · 获赞 3 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/pengpengzhou/article/details/105222504