0

我试图通过 Goland IDE 在 MongoDB 中插入数据。虽然连接正确并且在 IDE 输出中我得到了 ObjectID,但我仍然无法直接从终端看到结果。似乎数据库记录了一个没有任何信息的新文档......

OSX,MongoDB 是默认设置。驱动程序是'go.mongodb.org/mongo-driver'并且连接正确。Goland 在 2019.2.2

// go

type Student struct {
    name string
    sex string
}

newStu := Student{
    name: "Alice",
    sex: "Female",
}

collection := client.Database("mgo_1").Collection("student")

insertResult, err := collection.InsertOne(context.TODO(), newStu)

if err != nil {
   log.Fatal(err)
    }

fmt.Println(insertResult.InsertedID)

这是插入部分,我按照mongodb.com上的指南进行操作

> db.student.find()
{ "_id" : ObjectId("5d82d826f5e2f29823900275"), "name" : "Michael", "sex" : "Male" }
{ "_id" : ObjectId("5d82d845b8db68b150894f5a") }
{ "_id" : ObjectId("5d82dc2952c638d0970e9356") }
{ "_id" : ObjectId("5d82dcde8cf407b2fb5649e7") }

这是我在另一个终端查询的结果。除了第一个有一些内容外,其他三个是我尝试通过Goland 3次插入数据库的。

4

1 回答 1

0

所以你的结构看起来像这样:

type Student struct {
    name string
    sex string
}

nameand字段不以大写字母开头,sex因此它们不会被导出,因此对反射不可见。InsertOne毫无疑问,使用反射来找出其中的内容,newStuStudent结构没有导出字段,因此InsertOne根本看不到任何字段newStu

如果您将结构修复为具有导出字段:

type Student struct {
    Name string
    Sex string
}

然后InsertOne就能弄清楚里面有什么。MongoDB 接口应该自己计算从Name(Go) 到( nameMongoDB)的映射。Sexsex

于 2019-09-19T08:02:27.453 回答