gpt4 book ai didi

mongodb - 如何编写这些golang和mgo代码

转载 作者:IT王子 更新时间:2023-10-29 02:23:14 25 4
gpt4 key购买 nike

My mongodb data is here

 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
}

I try to write these code in golang , here is my golang code

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

}

After executing this code my result is like this

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

Problem is ,it does not show the NoOfusers and NoOfsales ,So is this possible to print the same output as present in above mongodb result without using any extra struct field like NoOfusers or NoOfsales

最佳答案

如果你只是想打印结果而不需要从 Details 结构中进行任何映射,那么将 var result []Details 替换为 var result []bson.M

如果你想映射到Details,那么你需要为这两个字段添加一个struct到Details中。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com