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"}}}}}//


