sql >> Base de Datos >  >> NoSQL >> MongoDB

Enviar una consulta MongoDB a un sistema diferente:¿convertir a JSON y luego decodificar en BSON? ¿Cómo hacerlo en el idioma Go?

Después de investigar un poco, encontré el mejson biblioteca, sin embargo, es solo para Marshalling, así que decidí escribir un Unmarshaller.

He aquí ejson (lo escribí), ahora mismo es un ejson muy simple -> bson convertidor, no hay bson -> ejson sin embargo, puedes usar mejson por eso.

Un ejemplo :

const j = `{"_id":{"$oid":"53c2ab5e4291b17b666d742a"},"last_seen_at":{"$date":1405266782008},"display_name":{"$undefined":true},
"ref":{"$ref":"col2", "$id":"53c2ab5e4291b17b666d742b"}}`

type TestS struct {
    Id          bson.ObjectId `bson:"_id"`
    LastSeenAt  *time.Time    `bson:"last_seen_at"`
    DisplayName *string       `bson:"display_name,omitempty"`
    Ref         mgo.DBRef     `bson:"ref"`
}

func main() {
    var ts TestS
    if err := ejson.Unmarshal([]byte(j), &ts); err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", ts)

    //or to convert the ejson to bson.M

    var m map[string]interface{}
    if err := json.Unmarshal([]byte(j), &m); err != nil {
        t.Fatal(err)
    }
    err := ejson.Normalize(m)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", m)

}