db.user.aggregate([{$project:{"_id":1,"NoOfUsers":{"$size":"$user"},"NoOfSales":{"$size":"$sales"},"user":1,"sales":1}}]).pretty()
{
    "_id" : ObjectId("57307906f051147d5317984e"),
    "user" : [
        {
            "firstName" : "chetan",
            "lastName" : "kumar",
            "age" : 23
        },
        {
            "firstName" : "nepolean",
            "lastName" : "dang",
            "age" : 26
        },
        {
            "firstName" : "Raj",
            "lastname" : "kumar",
            "age" : 26
        }
    ],
    "sales" : [
        {
            "firstName" : "ashu",
            "lastName" : "jha",
            "age" : 27
        }
    ],
    "NoOfUsers" : 3,
    "NoOfSales" : 1
}


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{"$project":bson.M{"_id":1,"NoOfUser":bson.M{"$size":"$user"},"user":1,"NoOfSales":bson.M{"$size":"$sales"},"sales":1,},}

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

}


[{"_id":"57307906f051147d5317984e","user":[{"firstName":"chetan","lastName":"kumar","age":23},{"firstName":"nepolean","lastName":"dang","age":26},{"firstName":"Raj","lastName":"","age":26}],"sales":[{"firstName":"ashu","lastName":"jha","age":27}]}]

最佳答案

如果只想打印结果而不从Details结构映射,则将var result []Details替换为var result []bson.M

如果要映射到Details,则需要将两个字段的结构添加到Details中。

关于mongodb - 如何编写这些golang和mgo代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37178221/

10-13 02:20