package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"log"
)
func main() {
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://username:password@ip:port/dbname?readPreference=secondaryPreferred"))
if err != nil {
panic(err)
}
if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
panic(err)
}
usersCollection := client.Database("dbname").Collection("tablename")
// 查询条件
filter := bson.D{{"somekey", "somevalue"}}
var result bson.M
err = usersCollection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Found a single document: %+v\n", result)
// result 是一个map ,可以直接访问
v := result["somekey"]
fmt.Println(v)
}
更多阅读