I was trying to insert data through Goland IDE in MongoDB. Though the connection is right and in the IDE output I got the ObjectID, I still cannot see the results from terminal directly. It seems that the database records a new document without any information...
OSX, MongoDB is at default setting. Driver is 'go.mongodb.org/mongo-driver' and the connection is right. Goland is at 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)
This is the insertion part, which I followed the guide on mongodb.com
> db.student.find()
{ "_id" : ObjectId("5d82d826f5e2f29823900275"), "name" : "Michael", "sex" : "Male" }
{ "_id" : ObjectId("5d82d845b8db68b150894f5a") }
{ "_id" : ObjectId("5d82dc2952c638d0970e9356") }
{ "_id" : ObjectId("5d82dcde8cf407b2fb5649e7") }
This is the result I query in another terminal. Except the first one which has some content, the other three are what I tried to insert to the database through Goland for three times.
So your struct looks like this:
type Student struct {
name string
sex string
}
The name
and sex
fields don't begin with capitals so they're not exported and thus not visible to reflection. InsertOne
undoubtedly uses reflection to figure out what's in newStu
but the Student
struct has no exported fields so InsertOne
can't see any fields in newStu
at all.
If you fix your struct to have exported fields:
type Student struct {
Name string
Sex string
}
then InsertOne
will be able to figure out what's in it. The MongoDB interface should figure out the mapping from Name
(Go) to name
(MongoDB) and Sex
to sex
on its own.