我是mgo的新手,需要一些帮助:我可以成功地连接并打印出数据库名称,收藏名称和项目的数量是集合,但不知道如何打印其中的内容和写回。在mgo中,什么等同于下面的mongodb shell命令?
- db.coll.find()
- document=({"user_id" : "xxx","password" :"xxx"....});
- db.coll.insert(document)//////////////////////////////////////////////////////////////////////
package main
import (
"fmt"
"time"
"gopkg.in/mgo.v2"
)
//const MongoDb details
const (
hosts = "mongodb.xxx:27017"
database = "myinfo"
username = "xxxxx"
password = "start123"
collection = "userdetails"
)
func main() {
info := &mgo.DialInfo{
Addrs: []string{hosts},
Timeout: 60 * time.Second,
Database: database,
Username: username,
Password: password,
}
session, err1 := mgo.DialWithInfo(info)
if err1 != nil {
panic(err1)
}
col := session.DB(database).C(collection)
datab := session.DB(database)
count, err2 := col.Count()
if err2 != nil {
panic(err2)
}
fmt.Println("Database Name:", datab.Name)
fmt.Println("Collection FullName:", col.FullName)
fmt.Println(fmt.Sprintf("Documents count: %d", count))
}下面是一个可以工作的版本:
package main
import (
"fmt"
"time"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
//const MongoDb details
const (
hosts = "xxx:27017"
database = "myinfo"
username = "xxxx"
password = "start123"
collection = "userdetails2"
)
type UserDetails struct {
_id bson.ObjectId `bson:"_id,omitempty"`
name string
phone string
}
func main() {
info := &mgo.DialInfo{
Addrs: []string{hosts},
Timeout: 60 * time.Second,
Database: database,
Username: username,
Password: password,
}
session, err1 := mgo.DialWithInfo(info)
if err1 != nil {
panic(err1)
}
col := session.DB(database).C(collection)
datab := session.DB(database)
count, err2 := col.Count()
if err2 != nil {
panic(err2)
}
fmt.Println("Database Name:", datab.Name)
fmt.Println("Collection FullName:", col.FullName)
fmt.Println(fmt.Sprintf("Documents count: %d", count))
var userDetail []bson.M
_ = col.Find(nil).All(&userDetail)
for _, v := range userDetail {
fmt.Println(v)
}
}发布于 2018-05-19 16:04:49
试试这个:
import (
"gopkg.in/mgo.v2/bson"
)
type UserDetails struct {
Id bson.ObjectId `bson:"_id,omitempty"`
UserId string `bson:"user_id"`
Password string `bson:"password"`
}
userDetails := []UserDetails{}
query := bson.M{
"user_id": "xxx",
"password" :"xxx"
}
err := col.Find(query).All(&userDetails)
if err != nil {
return
}
for _, userDetail := range userDetails {
fmt.Println(userDetail)
}我还没有测试这段代码。这只是一个例子。
发布于 2018-05-21 17:30:46
下面是一个相当简单的mgo包的例子:https://gist.github.com/border/3489566
我建议阅读官方文档以获取详细信息和参考资料。https://godoc.org/github.com/globalsign/mgo#Collection.Find
请注意,不再维护"gopkg.in/mgo.v2/bson"包。https://github.com/globalsign/mgo是该包的一个分支,由社区维护。
https://stackoverflow.com/questions/50423041
复制相似问题