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

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值