2017-03-06 52 views
0

我目前接收蒙戈聚集查询从一个有效载荷:转换地图[字符串]接口{}为有效蒙戈查询

[ 
    { 
    "$match": { 
     "isComplete": true 
     "accountId": "foo123" 
     "startTime": "2017-03-06T23:07:21.262Z" 
     "$or": [ { userId: "bar123" }, { userId: "bar235" } ] 
    } 
    }, 
    { 
    "$group": { 
     "_id": null, 
     "count": { 
     "$sum": 1 
     } 
    } 
    } 
] 

这是正在存储为map[string]interface{}。问题是$match子句可以是任意的查询,这意味着它可以包含ObjectIds和Dates。我试过手动将ID转换为bson.ObejectId和任何日期time.Times,但查询可能会变得非常复杂。

有谁知道从有效载荷中取出任意mongo查询并转换它的任何好方法吗?

回答

0

看来你需要解组到[]map[string]interface{}与该文章中的数组结构。

有了这样说,你可以做这样的事情(与当期的map[string]interface{}类型。

type Payload struct { 
    Message map[string]interface{} `json:"message"` 
} 

// If you are using it as a http HandleFunc 
func (s *Server) ProcessPayload() { 
    PayloadHandler := func(w http.ResponseWriter, r *http.Request) { 
     incoming := r.FormValue("message") 
     if incoming != "" { 
      var payload = new(Payload) 
      json.Unmarshal([]byte(incoming), payload) 

      go payload.FromPayload() 
     } 
    } 

    http.HandleFunc("/payload", PayloadHandler) 
} 

func (p *Payload) FromPayload() { 
    match, ok := p.Message["$match"] 
    if !ok { 
     return 
    } 
    // Do your work on the $match object 
} 
+0

我不得不更多地了解处理'$匹配的动态结构,当你面临的问题对象。 –