duanmei1885 2016-05-10 05:21
浏览 140
已采纳

如何在golang中使用$ unwind?

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.

  • 写回答

1条回答 默认 最新

  • dongqie7806 2016-05-10 05:35
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站