Golang Mgo - 如何查看结果?
Golang Mgo - How to view result?
看来我能够成功连接到我的 Mongo 数据库。我可以查看 collection 中有 30 条记录。我如何实际查看记录?
enter code here
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type User struct {
id bson.ObjectId `json:"-" bson:"_id"`
firstName string `json:"first_name"`
lastName string `json:"last_name"`
email string `json:"email"`
regId string `json:"registration_id"`
regKey string `json:"registration_key"`
password string `json:"password`
}
func main() {
session, err := mgo.Dial("XXX.XXX.XXX.XXX")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
//res := []User{}
c := session.DB("cd").C("auth_user")
res := []User{}
fmt.Println(c.Find(bson.M{}).All(&res))
fmt.Println(len(res))
fmt.Println(res)
fmt.Println(res[0])
fmt.Println(res[0].email)
}
上面的输出是:
30
[{ } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { }]
您需要export字段名称。
type User struct {
ID bson.ObjectId `json:"-" bson:"_id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
RegId string `json:"registration_id"`
RegKey string `json:"registration_key"`
Password string `json:"password`
}
BSON 编解码器忽略未导出的字段。
看来我能够成功连接到我的 Mongo 数据库。我可以查看 collection 中有 30 条记录。我如何实际查看记录?
enter code here
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type User struct {
id bson.ObjectId `json:"-" bson:"_id"`
firstName string `json:"first_name"`
lastName string `json:"last_name"`
email string `json:"email"`
regId string `json:"registration_id"`
regKey string `json:"registration_key"`
password string `json:"password`
}
func main() {
session, err := mgo.Dial("XXX.XXX.XXX.XXX")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
//res := []User{}
c := session.DB("cd").C("auth_user")
res := []User{}
fmt.Println(c.Find(bson.M{}).All(&res))
fmt.Println(len(res))
fmt.Println(res)
fmt.Println(res[0])
fmt.Println(res[0].email)
}
上面的输出是: 30 [{ } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { } { }]
您需要export字段名称。
type User struct {
ID bson.ObjectId `json:"-" bson:"_id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
RegId string `json:"registration_id"`
RegKey string `json:"registration_key"`
Password string `json:"password`
}
BSON 编解码器忽略未导出的字段。