亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 golang 中為嵌套數組 $push?

如何在 golang 中為嵌套數組 $push?

Go
忽然笑 2022-01-10 19:11:23
我嘗試使用$push. 這是我的 json 文件{    "_id" : ObjectId("57307906f051147d5317984e"),    "user" : [        {            "firstName" : "chetan",            "lastName" : "kumar",            "age" : 23,            "sales" : [                {            "firstName" : "ashu",            "lastName" : "jha",            "age" : 27                }            ],        },        {            "firstName" : "nepolean",            "lastName" : "dang",            "age" : 26        },        {            "firstName" : "Raj",            "lastname" : "kumar",            "age" : 26        }    ],}現在這是我在這里嘗試執行的 golang 代碼package mainimport(    "fmt"    "log"    "net/http"        //"encoding/json"    "github.com/gorilla/mux"        "gopkg.in/mgo.v2"        "gopkg.in/mgo.v2/bson")type User struct{    SALES       []Sales     `json:"sales" bson:"sales"`    FIRSTNAME   string      `json:"firstName" bson:"firstName"`    LASTNAME    string      `json:"lastName" bson:"lastName"`    AGE     int     `json:"age" bson:"age"`}type Sales struct{    FIRSTNAME   string      `json:"firstName" bson:"firstName"`    LASTNAME    string      `json:"lastName" bson:"lastName"`    AGE     int     `json:"age" bson:"age"`}type Details struct{    ID  bson.ObjectId   `json:"_id" bson:"_id"`    USER    []User      `json:"user" bson:"user"`}func detail(w http.ResponseWriter, r *http.Request){    session, err := mgo.Dial("127.0.0.1")        if err != nil {                panic(err)        }else{                fmt.Println("dial")        }        defer session.Close()        session.SetMode(mgo.Monotonic, true)        c := session.DB("userdb").C("user")        addsales:= []Sales{Sales{            FIRSTNAME : "chetan",            LASTNAME : "kumar",            AGE : 24,            },        }
查看完整描述

2 回答

?
達令說

TA貢獻1821條經驗 獲得超6個贊

您正在Sales為單個項目推送一個帶有語法的數組。

它應該是Sales要推送的單個對象:


addsales:= Sales{

    FIRSTNAME : "chetan",

    LASTNAME : "kumar",

    AGE : 24,

},

change := bson.M{"$push":bson.M{"user.$.sales":addsales}}

或使用$each修飾符推送多個項目:


addsales:= []Sales{Sales{

    FIRSTNAME : "chetan",

    LASTNAME : "kumar",

    AGE : 24,

    },

}

change := bson.M{"$push":bson.M{"user.$.sales":bson.M{"$each":addsales}}}


查看完整回答
反對 回復 2022-01-10
?
瀟湘沐

TA貢獻1816條經驗 獲得超6個贊

addsales:= []Sales{Sales{

            FIRSTNAME : "chetan",

         LASTNAME : "kumar",

         AGE : 24,

          },

        }


    match := bson.M{"user.firstName" : "nepolean"}

    change := bson.M{"$push":bson.M{"user.$.sales":bson.M{"$each":addsales}}}



    err = c.Update(match,change)

    if err !=nil{

        panic(err)      

    }else{

    fmt.Println("success")

    }


查看完整回答
反對 回復 2022-01-10
  • 2 回答
  • 0 關注
  • 282 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號