mongodb mgo custom _id

时间:2018-05-28 07:42:59

标签: mongodb mgo

我使用此方法创建/插入文档:

document5=({"_id": {"date" : 23, "hour" : 11}, "value" : {"avg_cpu" : 2.558333333333333, "avg_cpu_rate" : 18.419999999999998} })db.userdetails2.insert(document5)

导致了这个:

{        "_id" : {                "date" : 23,                "hour" : 11        },        "value" : {                "avg_cpu" : 2.558333333333333,                "avg_cpu_rate" : 18.419999999999998

我怎么能用golang mgo做到这一点?

问题在于我需要将数据插入_id,但这不是外部可用的。

2 个答案:

答案 0 :(得分:0)

如果我已经理解了你要做的正确的事情,这应该有用。

type (
    IdRec struct {
        Date int `bson:"date"`
        Hour int `bson:"hour"`
    }

    CpuRec struct {
        AvgCpu     float64 `bson:"avg_cpu"`
        AvgCpuRate float64 `bson:"avg_cpu_rate"`
    }

    DocRec struct {
        ID    IdRec  `bson:"_id"`
        Value CpuRec `bson:"value"`
     }
)

    func saveRecord(){
        newRec := DocRec{}
        newRec.ID.date = 23
        newRec.ID.hour = 11
        newRec.Value.AvgCpu = 2.558333333333333
        newRec.Value.AvgCpuRate = 18.419999999999998

        session := MongoSession.Copy()
        defer session.Close()

        theCollection := session.DB(DbName).C(CollectionName)
        err := theCollection.Insert(&newRec)
        if err != nil {
            doSomething(err)
        }
    }

答案 1 :(得分:0)

谢谢,我会尝试一下,但是我提出了这个并且它有效:

package main

import (
    "fmt"
    "time"

    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

//const MongoDb details
const (
    hosts      = "xxxxx:27017"
    database   = "xxxx"
    username   = "xxxx"
    password   = "xxxx"
    collection = "xxxx"
)

type UserDetails struct {
    Id    IdType
    Value ValueType
}

type IdType struct {
    Date string
    Hour string
}

type ValueType struct {
    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)
    }

    //Write Data//
    item := UserDetails{Id: IdType{Date: "23", Hour: "13"}, Value: ValueType{Name: "some-name", Phone: "123 333"}}

    _, err := col.Upsert(bson.M{"_id": item.Id}, bson.M{"Value": item.Value})

    if err != nil {
        panic(err)
    }

    //Read Data//
    var userDetail []bson.M
    //#1 Search a document with Name= xxxx
    //_ = col.Find(bson.M{"Name": "xxxx"}).All(&userDetail)

    //#2 Search All documents
    _ = col.Find(nil).All(&userDetail)
    for _, v := range userDetail {
        fmt.Println(v)
    }

}