當我將一組檔案插入 MongoDB Atlas 集合時,我收到以下錯誤訊息:
2021/12/23 09:37:03 服務器選擇錯誤:背景關系取消,當前拓撲:{ 型別:ReplicaSetNoPrimary,服務器:[{ 地址:cluster-attitude-shard-00-00.o7pjk.mongodb.net:27017,型別: 未知 }, { 地址: cluster-attitude-shard-00-01.o7pjk.mongodb.net:27017, 型別: Unknown }, { 地址: cluster-attitude-shard-00-02.o7pjk.mongodb.net:27017 , 型別:未知 }, ] }
我使用下一個代碼:
interfaz_slice := ToInterfaceSlice(students)
_, err := coleccion.InsertMany(ctx, interfaz_slice)
函式“ToInterfaceSlice”接收結構切片并回傳介面切片
我不明白我在哪里犯了錯誤
提前致謝
問題的新部分:
檔案片段“main.go”:
func main() {
var students []data.TypeStudent
absPath, _ := filepath.Abs("data/students.csv")
students = data.LeerFichero(absPath)
data.ConectaBD()
data.InsertaColleccionEstudiantes(students)
}
檔案片段“students.go”:
type TypeStudent struct {
FirstName string `bson:"first_name" json:"first_name"`
LastName string `bson:"last_name" json:"last_name"`
Class string `bson:"class" json:"class"`
}
func ToInterfaceSlice(lista []TypeStudent) []interface{} {
iface := make([]interface{}, len(lista))
for i := range lista {
iface[i] = lista[i]
}
return iface
}
檔案片段“basedatos.go”:
func ConectaBD() {
cliente_local, err := mongo.NewClient(options.Client().ApplyURI(cadena_conexion))
if err != nil {
log.Fatal(err)
}
ctx, cancelar = context.WithTimeout(context.Background(), 10*time.Second)
err = cliente_local.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer cancelar()
mongo_cliente = cliente_local.Database("attitude")
log.Println("[ ]Connected to MongoDB Atlas")
}
func InsertaColleccionEstudiantes(students []TypeStudent) {
coleccion = mongo_cliente.Collection("students")
interfaz_slice := ToInterfaceSlice(students)
log.Println("[ ]A slice of interfaces are inserted directly into MONGODB")
_, err := coleccion.InsertMany(ctx, interfaz_slice)
if err != nil {
log.Fatal(err)
}
}
uj5u.com熱心網友回復:
資訊是不夠的。檢查是否IP被列入白名單。還要指定您正在使用的背景關系。您可以嘗試使用context.TODO().
我試過了,效果很好。
確保您的連接成功。還使用 關閉連接defer。
這是您可以嘗試使用的示例代碼:
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
// begin insertMany
coll := client.Database("insertDB").Collection("haikus")
docs := []interface{}{
bson.D{{"title", "Record of a Shriveled Datum"}, {"text", "No bytes, no problem. Just insert a document, in MongoDB"}},
bson.D{{"title", "Showcasing a Blossoming Binary"}, {"text", "Binary data, safely stored with GridFS. Bucket the data"}},
}
result, err := coll.InsertMany(context.TODO(), docs)
if err != nil {
panic(err)
}
為了更好地理解,請參閱此鏈接:https : //raw.githubusercontent.com/mongodb/docs-golang/master/source/includes/usage-examples/code-snippets/insertMany.go
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/393696.html
標籤:去 mongodb-图集
