Go 使用mongodb
安装 mkdir go-mongo go mod init go-mongo go get go.mongodb.org/mongo-driver/mongo 使用 数据库里面有一条这样的数据: { "_id": { "$oid": "6252912ec4495f97bccf41aa" }, "title": "My Mongo Post", "create_time": { "$date": "2022-04-10T10:33:45.149Z" }, "viewer": 201 } 连接数据库 // 关键代码 const MONGO_URI = "mongodb://localhost:27017/test" client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(MONGO_URI)) // 优雅关闭连接 defer client.Disconnect(context.TODO()) 数据查询 首先获取到对应的database以及collection coll := client.Database("test").Collection("post") 然后查询: coll := client.Database("test").Collection("post") var result bson.M // 需要一个bson.M 对象,用于存储查询回来的数据 // FindOne 接受2个参数,一个context,一个filter,filter 为 bson.D类型 err = coll.FindOne(context.TODO(), bson.D{}).Decode(&result) if err == mongo.ErrNoDocuments { fmt.Printf("No document found.\n") return } else if err != nil { panic(err) } fmt.Printf("Found document result: %s\n", result) 数据查询注意点: 需要一个 bson.M 对象,用于存储返回的数据 Collection.FindOne 接受3个参数,ctx、filter和opts,返回的是一个 SingleResult 对象 ctx可以为nil,如果为nil的话,默认会创建一个 context.Backgroud的context filter为查询条件,为 bson.D 类型,上面代码默认为空,意味着查询任意一条数据。也可以指定特定的条件,如 bson.d{{"title", "first post"}},意味着查询 tile 为 first post 的文档。 opts:类型为 options.FindOneOptions 类型,查询的额外条件,比如限定返回的具体字段:&options.FindOneOptions{Projection: map[string]int{"_id": 0}},这个options禁止返回_id字段。 使用 SingleResult.Decode方法将返回的SingleResult反序列化为 bson.M 对象,SingleResult.Decode(&result) 上述查询输出: ...