mgo操作MongoDB读写求助:实现查询与插入功能
Hey there! I see you've already got mgo connected to your MongoDB instance and can fetch basic metadata—great start! Let's walk through how to implement those three MongoDB Shell operations in mgo, using your existing code as a base.
1. Equivalent of db.coll.find()
To retrieve and print all documents in a collection (just like db.coll.find()), mgo provides the Find() method combined with All() to load results into a slice. You have two common options for storing the results:
Option 1: Use bson.M (flexible map)
This is great if you don't want to define a struct for your document structure:
var docs []bson.M // Find(nil) means "match all documents" err := col.Find(nil).All(&docs) if err != nil { panic(err) } // Print each document for _, doc := range docs { fmt.Printf("Document: %+v\n", doc) }
Option 2: Use a custom struct (type-safe)
If you know your document schema, defining a struct is cleaner. Important: Struct fields must be exported (start with a capital letter) so mgo can serialize/deserialize them. Let's fix your UserDetails struct and use it:
type UserDetails struct { ID bson.ObjectId `bson:"_id,omitempty"` Name string `bson:"name"` Phone string `bson:"phone"` } // Fetch all documents into the struct slice var users []UserDetails err := col.Find(nil).All(&users) if err != nil { panic(err) } // Print each user for _, user := range users { fmt.Printf("User: ID=%s, Name=%s, Phone=%s\n", user.ID.Hex(), user.Name, user.Phone) }
2. Equivalent of creating a document (document={"user_id" : "xxx","password" :"xxx"....};)
Again, you can use either a bson.M map or a struct instance to represent your document:
Using bson.M
newDoc := bson.M{ "user_id": "user123", "password": "secure123", // Add other fields as needed }
Using a struct
First, update your struct to include the new fields:
type UserDetails struct { ID bson.ObjectId `bson:"_id,omitempty"` UserID string `bson:"user_id"` Password string `bson:"password"` Name string `bson:"name"` Phone string `bson:"phone"` } // Create a new instance newUser := UserDetails{ UserID: "user123", Password: "secure123", Name: "John Doe", Phone: "987654321", }
3. Equivalent of db.coll.insert(document)
To insert your document into the collection, use mgo's Insert() method. You can insert a single document or multiple at once:
Insert a single document (using bson.M)
err := col.Insert(newDoc) if err != nil { panic(err) } fmt.Println("Document inserted successfully!")
Insert a single document (using a struct)
err := col.Insert(&newUser) if err != nil { panic(err) } fmt.Println("User inserted successfully!")
Insert multiple documents
doc1 := bson.M{"user_id": "user456", "password": "secure456"} doc2 := UserDetails{UserID: "user789", Password: "secure789"} err := col.Insert(doc1, &doc2) if err != nil { panic(err) } fmt.Println("Multiple documents inserted successfully!")
Full Working Example
Here's your original code with all the above operations integrated, plus best practices like closing the session:
package main import ( "fmt" "time" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) // MongoDB details const ( hosts = "mongodb.xxx:27017" database = "myinfo" username = "xxxxx" password = "start123" collection = "userdetails" ) type UserDetails struct { ID bson.ObjectId `bson:"_id,omitempty"` UserID string `bson:"user_id"` Password string `bson:"password"` Name string `bson:"name"` Phone string `bson:"phone"` } func main() { info := &mgo.DialInfo{ Addrs: []string{hosts}, Timeout: 60 * time.Second, Database: database, Username: username, Password: password, } session, err := mgo.DialWithInfo(info) if err != nil { panic(err) } defer session.Close() // Always close the session when done col := session.DB(database).C(collection) datab := session.DB(database) // Print collection metadata count, err := col.Count() if err != nil { panic(err) } fmt.Println("Database Name:", datab.Name) fmt.Println("Collection FullName:", col.FullName) fmt.Printf("Documents count: %d\n", count) // 1. Fetch and print all documents (db.coll.find()) var users []UserDetails err = col.Find(nil).All(&users) if err != nil { panic(err) } fmt.Println("\nAll documents in collection:") for _, user := range users { fmt.Printf("- ID: %s, UserID: %s, Name: %s\n", user.ID.Hex(), user.UserID, user.Name) } // 2. Create a new document newUser := UserDetails{ UserID: "new_user_001", Password: "new_pass_123", Name: "Jane Smith", Phone: "555555555", } // 3. Insert the document (db.coll.insert()) err = col.Insert(&newUser) if err != nil { panic(err) } fmt.Println("\nNew user inserted successfully!") // Verify the insert by counting again newCount, err := col.Count() if err != nil { panic(err) } fmt.Printf("Updated documents count: %d\n", newCount) }
内容的提问来源于stack exchange,提问作者Csaba Dobo

