mongodb - Mongo shell 和代码结果返回不同的结果
问题描述
我是 mongodb 的新手,我试图效仿一个例子,但无法检查 mongo shell 中的数据,因为它们返回不同的结果
我的代码
package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
//Trainer You will be using this Trainer type later in the program
type Trainer struct {
Name string
Age int
City string
}
func main() {
// Set client options
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
// Connect to MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// Check the connection
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
collection := client.Database("db_test").Collection("trainers")
ash := Trainer{"Ash", 10, "Pallet Town"}
misty := Trainer{"Misty", 10, "Cerulean City"}
brock := Trainer{"Brock", 15, "Pewter City"}
trainers := []interface{}{ash, misty, brock}
insertResult, err := collection.InsertMany(context.TODO(), trainers)
if err != nil {
log.Fatal(err)
}
fmt.Println("Inserted a single document: ", insertResult.InsertedIDs)
result, err := collection.Find(context.TODO(), bson.D{}, options.Find())
if err != nil {
log.Fatal(err)
}
fmt.Println("Find Failed.")
for result.Next(context.TODO()) {
var singleRow Trainer
err := result.Decode(&singleRow)
if err != nil {
log.Fatal(err)
}
fmt.Println(singleRow.Name, "+", singleRow.Age)
}
fmt.Println("Find finished")
err = client.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
fmt.Println("Connection to MongoDB closed.")
}
这返回
Connected to MongoDB!
Inserted a single document: [ObjectID("5da929e60a2ef8952d92ce8c") ObjectID("5da929e60a2ef8952d92ce8d") ObjectID("5da929e60a2ef8952d92ce8e")]
Find Failed.
Ash + 10
Misty + 10
Brock + 15
Find finished
Connection to MongoDB closed.
蒙戈壳
是因为 mongo shell 和我的 go 代码连接到不同的集群还是什么?我也尝试过使用指南针,它也显示出与 mongo shell 不同的结果。我怎么知道外壳工作正常?
我的路径环境设置为“C:\Program Files\MongoDB\Server\4.2\bin”所以我认为这没有问题
解决方案
替换以下行后,尝试运行您的 Go 代码
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
有了这个
clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb")
推荐阅读
- mongodb - 填充方法未填充我的评论数组
- multiprocessing - 使用 torch.multiprocessing 时 Pytorch 模型前进速度降低
- html - 表格上方出现未知空格(在 asp.net 数据列表中)
- javascript - 嵌套循环解决方案的时间复杂度如何比使用缓存的解决方案最差?
- django - Django React:API HTML 响应不呈现浏览器
- android - View Pager 2 /Recycler 视图因不一致而崩溃
- jquery - 摆脱移动视图上的水平滚动条
- javascript - State ValueChange 无法重新渲染组件
- swift - 范围限制的“无法推断通用参数 'T'”
- spring - 包含的 gradle 构建中的 Spring 依赖管理