You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Golang mgo插入含自定义嵌套结构_id的MongoDB文档?

Replicating Custom Nested _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 _id Handling: The nested ID struct is correctly serialized to MongoDB's _id field thanks to the bson:"_id" tag. This works exactly like your Shell command—no extra steps needed to "hide" or specially handle the _id field; mgo handles the mapping automatically.
  • Field Matching: Double-check that the bson tags match the exact field names in your MongoDB document (e.g., avg_cpu vs AvgCPU in the struct—tags are case-sensitive!).
  • Validation: To confirm the insert worked, run this in your MongoDB Shell:
    db.userdetails2.find({"_id.date": 23, "_id.hour": 11})
    
    You'll see the exact document you inserted, matching the result from your original Shell command.

内容的提问来源于stack exchange,提问作者Csaba Dobo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:32:31