您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在mongo-go-driver中使用ParseExtJSONArray()在聚合管道中解析扩展的JSON日期

如何在mongo-go-driver中使用ParseExtJSONArray()在聚合管道中解析扩展的JSON日期

MongoDB扩展JSON背后的想法是用纯JSON 表示二进制JSON(BSON)类型。

通用语法是将对象表示为单个嵌入式文档。例如,BSON二进制对象表示为document {"$binary": "<binary data>"}$键字段中的前缀指示类型。BSON日期对象也是如此。

方法bson.ParseExtJSONArray()期望扩展的JSON类型为文档,而不是MongoDB点表示法表达式。例如,而不是下面:

{ "$match": { "dateTimeGMT.$date":"2018-08-22T09:29:25.000Z" } }

方法期望:

{ "$match": { "dateTimeGMT": {"$date":"2018-08-22T09:29:25.000Z" } } }

您还可以在Unix Epoch中提供日期值,例如:

{ "$match": { "dateTimeGMT": {"$date": { "$numberLong": "1546300800"} } } }

使用mongo-go-driver / bson,示例如下:

raw := `[ { "$match": {"dateTimeGMT": {"$date": {"$numberLong": "1530962624753" } } } } ]`
pipeline, err := bson.ParseExtJSONArray(raw)
cursor, err := collection.Aggregate(context.Background(), pipeline)

特别说明: 您可以ParseExtJSONArray()在迭代结果值并将其传递给聚合之前进行调试。例如:

toConvert := `[
   { "$lookup": {
        "from": "anotherCollection",
        "localField": "foreignKey",
        "foreignField": "_id",
        "as": "someField"
    }},
    { "$match": {"dateTimeGMT":{"$lt": {"$date": "2019-01-10T09:29:25.000Z" } } } }
]`
pipeline, err := bson.ParseExtJSONArray(toConvert)

it, err := bson.NewArrayIterator(pipeline)
for it.Next() {
    fmt.Println(it.Value().MutableDocument().ToExtJSON(true))
}

//Outputs : 
//   {"$lookup":{"from":"anotherCollection","localField":"foreignKey","foreignField":"_id","as":"someField"}}
//   {"$match":{"dateTimeGMT":{"$lt":{"$date":{"$numberLong":"1547112565000"}}}}}
//
mongodb 2022/1/1 18:14:01 有726人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶