如何在Golang中对嵌套数组进行$push操作?

huangapple go评论113阅读模式
英文:

How to $push in golang for nested array?

问题

我尝试使用$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 main

import (
    "fmt"
    "log"
    "net/http"
    "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,
    }}
    fmt.Println(addsales)
    match := bson.M{"firstName": "nepolean"}
    change := bson.M{"$push": bson.M{"user.$.sales": addsales}}
    err = c.Update(match, change)
    if err != nil {
        panic(err)
    } else {
        fmt.Println("success")
    }
}

func main() {
    router := mux.NewRouter().StrictSlash(true)
    router.HandleFunc("/detail", detail)
    log.Fatal(http.ListenAndServe(":9080", router))
}

这是执行后的输出:

/Desktop$ go run arrayupdate.go
dial
[{chetan kumar 24}]
success

请注意,这只是代码的一部分,我只提供了执行后的输出。

英文:

I tried to push some data in nested array using $push. Here is my json file

{
"_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
}
],
}

Now here is my golang code which I tried here to execute

package main
import(
"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,
},
}
fmt.Println(addsales)
match := bson.M{"firstName" : "nepolean"}
change := bson.M{"$push":bson.M{"user.$.sales":addsales}}
err = c.Update(match,change)
if err !=nil{
panic(err)		
}else{
fmt.Println("success")
}
}
func main(){
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/detail",detail)
log.Fatal(http.ListenAndServe(":9080", router))
}

Here, is my OutPut after executing

/Desktop$ go run arrayupdate.go dial [{chetan kumar 24}] 2016/05/24
12:39:48 http: panic serving 127.0.0.1:43928: not found goroutine 5
[running]: net/http.(*conn).serve.func1(0xc820082200)
/usr/local/go/src/net/http/server.go:1389 +0xc1 panic(0x7c6bc0,
0xc82000b080) 	/usr/local/go/src/runtime/panic.go:426 +0x4e9
main.detail(0x7f4a62bf9900, 0xc8200735f0, 0xc8200d6000)
/home/joybynature/Desktop/arrayupdate.go:93 +0x7a6
net/http.HandlerFunc.ServeHTTP(0x91d9f0, 0x7f4a62bf9900, 0xc8200735f0,
0xc8200d6000) 	/usr/local/go/src/net/http/server.go:1618 +0x3a
github.com/gorilla/mux.(*Router).ServeHTTP(0xc820012550,
0x7f4a62bf9900, 0xc8200735f0, 0xc8200d6000)
/home/joybynature/src/github.com/gorilla/mux/mux.go:107 +0x285
net/http.serverHandler.ServeHTTP(0xc820082180, 0x7f4a62bf9900,
0xc8200735f0, 0xc8200d6000) 	/usr/local/go/src/net/http/server.go:2081
+0x19e net/http.(*conn).serve(0xc820082200) 	/usr/local/go/src/net/http/server.go:1472 +0xf2e created by
net/http.(*Server).Serve 	/usr/local/go/src/net/http/server.go:2137
+0x44e

答案1

得分: 13

您正在将一个 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}}}
英文:

You are pushing an array of Sales with syntax for a single item.
It should be either a single Sales object to push:

addsales:= Sales{
FIRSTNAME : "chetan",
LASTNAME : "kumar",
AGE : 24,
},
change := bson.M{"$push":bson.M{"user.$.sales":addsales}}

or use $each modifier to push multiple items:

addsales:= []Sales{Sales{
FIRSTNAME : "chetan",
LASTNAME : "kumar",
AGE : 24,
},
}
change := bson.M{"$push":bson.M{"user.$.sales":bson.M{"$each":addsales}}}

答案2

得分: 0

添加销售:= []销售{销售{
FIRSTNAME : "chetan",
LASTNAME : "kumar",
AGE : 24,
},
}

匹配 := bson.M{"user.firstName" : "nepolean"}
更改 := bson.M{"$push":bson.M{"user.$.sales":bson.M{"$each":添加销售}}}

错误 = c.Update(匹配,更改)
如果 错误 != nil{
panic(错误)
}else{
fmt.Println("成功")
}

英文:
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")
}

huangapple
  • 本文由 发表于 2016年5月24日 15:53:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/37407476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定