简体   繁体   中英

How to use $unwind in golang?

I want the result in go as the mongo shell provide me.

In mongo shell the data is like this:

db.user.aggregate([{$unwind:"$user"}]).pretty()    
{
    "_id" : ObjectId("57307906f051147d5317984e"),
    "user" : {
        "firstName" : "chetan",
        "lastName" : "kumar",
        "age" : 23
    },
    "sales" : [
        {
            "firstName" : "ashu",
            "lastName" : "jha",
            "age" : 27
        }
    ]
}
{
    "_id" : ObjectId("57307906f051147d5317984e"),
    "user" : {
        "firstName" : "nepolean",
        "lastName" : "dang",
        "age" : 26
    },
    "sales" : [
        {
            "firstName" : "ashu",
            "lastName" : "jha",
            "age" : 27
        }
    ]
}

But in go

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{
    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"`
    SALES   []Sales     `json:"sales" bson:"sales"`
}

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")


       var result []Details


    o1 := bson.M{
        "$unwind":"$user",
    }


        operations := []bson.M{o1}
    pipe := c.Pipe(operations)
    err = pipe.All(&result)
        if err != nil {
                log.Fatal(err)
        }
        res1B, _ := json.Marshal(result)
        fmt.Fprintf(w,string(res1B))
}

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

}

Result is like this:

 [{"_id":"57307906f051147d5317984e",
"user":null,
"sales":[{
"firstName":"ashu","lastName":"jha","age":27}]},{"_id":"57307906f051147d5317984e",
"user":null,
"sales":[{
"firstName":"ashu","lastName":"jha","age":27}]}]        

But it shows "user": null , I want the reult as provide by mongo shell.

Because the mapping is invalid, after $unwind on $user , you should expect every single result only contains a single user, therefore, User shouldn't be an array .

type Details struct{
    ID  bson.ObjectId   `json:"_id" bson:"_id"`
    USER    []User      `json:"user" bson:"user"`
    SALES   []Sales     `json:"sales" bson:"sales"`
}

Should be changed to:

type Details struct{
    ID  bson.ObjectId   `json:"_id" bson:"_id"`
    USER    User      `json:"user" bson:"user"`
    SALES   []Sales     `json:"sales" bson:"sales"`
}

Since you might need two types of responses, one is normal response, another one is $unwind response which is current one, you can create another type for it:

type UnwindDetails struct{
    ID  bson.ObjectId   `json:"_id" bson:"_id"`
    USER    User      `json:"user" bson:"user"`
    SALES   []Sales     `json:"sales" bson:"sales"`
}

and remain your original type

type Details struct{
    ID  bson.ObjectId   `json:"_id" bson:"_id"`
    USER    []User      `json:"user" bson:"user"`
    SALES   []Sales     `json:"sales" bson:"sales"`
}

So you got to modify the type of result variable to:

var result []UnwindDetails

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM