如何使用Golang mgo插入含自定义嵌套结构_id的MongoDB文档?
_id Insert with Go's mgo Driver Got it, let's break down exactly how to replicate that MongoDB Shell insert you did using the mgo driver in Go. The core challenge here is properly mapping your nested _id and value structures to Go types so mgo can serialize them correctly into MongoDB.
Step 1: Define Matching Go Structs
First, you need to create Go structs that mirror the nested document structure you're using. Remember that mgo relies on exported fields (capitalized names) and bson tags to map to MongoDB's field names:
// ID represents the nested custom _id structure type ID struct { Date int `bson:"date"` Hour int `bson:"hour"` } // Value holds the CPU metrics nested under the "value" field type Value struct { AvgCPU float64 `bson:"avg_cpu"` AvgCPURate float64 `bson:"avg_cpu_rate"` } // UserDetail is the top-level struct representing your full document type UserDetail struct { ID ID `bson:"_id"` // Maps directly to MongoDB's _id field Value Value `bson:"value"` }
The bson:"_id" tag on the ID field tells mgo to serialize this nested struct as the document's _id—exactly what you did in the Shell.
Step 2: Connect to MongoDB and Insert the Document
Next, write the code to connect to your MongoDB instance, create the document instance, and insert it into the userdetails2 collection:
package main import ( "log" "gopkg.in/mgo.v2" ) // Place the struct definitions here func main() { // Connect to your MongoDB server (adjust the URI to match your setup) session, err := mgo.Dial("mongodb://localhost:27017") if err != nil { log.Fatalf("Couldn't connect to MongoDB: %v", err) } defer session.Close() // Ensure we clean up the connection when done // Optional: Set consistency mode (Strong ensures reads reflect writes immediately) session.SetMode(mgo.Strong, true) // Get your target database and collection db := session.DB("your_database_name") // Replace with your actual DB name collection := db.C("userdetails2") // Create the document matching your Shell insert doc := UserDetail{ ID: ID{ Date: 23, Hour: 11, }, Value: Value{ AvgCPU: 2.558333333333333, AvgCPURate: 18.419999999999998, }, } // Insert the document into the collection if err := collection.Insert(doc); err != nil { log.Fatalf("Failed to insert document: %v", err) } log.Println("Document inserted successfully!") }
Key Notes for Your Use Case
- Custom
_idHandling: The nestedIDstruct is correctly serialized to MongoDB's_idfield thanks to thebson:"_id"tag. This works exactly like your Shell command—no extra steps needed to "hide" or specially handle the_idfield; mgo handles the mapping automatically. - Field Matching: Double-check that the
bsontags match the exact field names in your MongoDB document (e.g.,avg_cpuvsAvgCPUin the struct—tags are case-sensitive!). - Validation: To confirm the insert worked, run this in your MongoDB Shell:
You'll see the exact document you inserted, matching the result from your original Shell command.db.userdetails2.find({"_id.date": 23, "_id.hour": 11})
内容的提问来源于stack exchange,提问作者Csaba Dobo

