gpt4 book ai didi

json - 向不同系统发送 MongoDB 查询 : converting to JSON and then decoding into BSON? Go 语言如何实现?

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

我需要将 MongoDB 查询传输到不同的系统。出于这个原因,我想使用 MongoDB Extended JSON .我需要这样做主要是因为我在查询中使用日期比较。

所以,问题的核心是我需要将在 node.js 后端生成的 MongoDB 查询传输到另一个用 Go< 编写的后端/em> 语言。

直觉上,通过 REST 发送此查询的最明显格式是 JSON。但是,MongoDB 查询不完全是 JSON,而是 BSON,它包含特殊的日期结构。

因此,我们的想法是使用 MongoDB Extended JSON 将查询转换为 JSON作为特殊构造的表示形式。经过一些测试后,很明显这些查询不起作用。 MongoDB shell 和通过 node.js 发送的查询都需要特殊的 ISODatenew Date 结构。

最后,真正的问题是:考虑到MongoDB Extended JSON,是否有从 JSON 编码/解码到 BSON 的函数? , 在 JavaScript (node.js) 和 Go 语言中?

更新

Node.js编码包

显然 there is a node.js package解析和字符串化 BSON/JSON。这样,我的问题就解决了一半。我想知道 Go 语言中是否有类似的东西。

示例查询

例如,以下查询在普通 BSON 中:

{ Tmin: { $gt: ISODate("2006-01-01T23:00:00.000Z") } }

翻译成MongoDB Extended JSON,就变成了:

{ "Tmin": { "$gt" : { "$date" : 1136156400000 }}}

最佳答案

经过一些研究,我找到了 mejson库,但它仅用于编码,所以我决定编写一个 Unmarshaller。

ejson (我写的),现在它是一个非常简单的ejson -> bson 转换器,没有bson -> ejson 但是,您可以为此使用 mejson

example :

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)

}

关于json - 向不同系统发送 MongoDB 查询 : converting to JSON and then decoding into BSON? Go 语言如何实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25218061/

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