【问题标题】:How to unmarshal non-trivial mongo return bson struct如何解组非平凡的 mongo 返回 bson 结构
【发布时间】:2020-12-16 22:22:42
【问题描述】:

mongo的返回是这样的:

[
    {
        "_id": "XXXXX-XXXX-XXXXXXXXXXXXXXX",
        "InternetGatewayDevice": {
            "WANDevice": {
                "1": {
                    "_instance": true,
                    "_writable": false
                },
                "2": {
                    "_instance": true,
                    "_writable": false
                },
                ...
                "_object": true,
                "_timestamp": {
                    "$date": "2020-11-23T04:14:13.202Z"
                },
                "_writable": false
            }
        }
    }
]
  • WanDevice.1WanDevice.2 不固定。可以是n 对象。
  • 当返回是一个 json 字符串时,UnmarshalJSON 有效。因为WanDevice.[id]id 是连续的而不是重复的,所以我可以将WanDevices 的数组创建到InternetGatewayDevice 结构中

可以成为一种“解组”从 mongo 返回的方法,而无需创建这样的结构吗?

type Device struct {
    InternetGatewayDevice InternetGatewayDevice `json:"InternetGatewayDevice" bson:"InternetGatewayDevice"`
}

type InternetGatewayDevice struct {
    WANDevice WANDevice `json:"WANDevice" bson:"WANDevice"`
}

type WANDevice struct {
    DeviceNum1 `json:"1" bson:"1"`
    DeviceNum1 `json:"2" bson:"2"`
    DeviceNum1 `json:"3" bson:"3"`
    DeviceNum1 `json:"4" bson:"4"`
    .....
}
  • 我这样称呼它:
    collection := m.Client.Database(acs.Mongo.Database).Collection("devices")
    filter := bson.D{
        {"InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANPPPConnection.2.MACAddress._value", parsedMac},
    }

    response := &models.Device{}
    err = collection.FindOne(context.TODO(), filter).Decode(response)

【问题讨论】:

  • 为什么不能用简单的地图?
  • 不幸的是,回报比我放在这里的例子大得多,如果我制作&map[string]interface{}{}回报的地图,那么可能会消耗更多的内存不是吗?
  • 如果你的内存快用完了,地图键使用的额外内存会让你陷入困境,那么我会说你有更大的问题需要担心。使用适合问题的数据类型。如果您有内存问题,请通过分析和实验直接解决。

标签: mongodb go unmarshalling bson


【解决方案1】:

您可以创建自定义 UnmarshalJSON,如下所示: https://play.golang.org/p/FdW064a9RDT

【讨论】:

  • 我试过了,但是 mongo findOne 中的decode 函数返回使用bson.UnmarshalWithRegistry 方法,不幸的是它不会调用自定义的UnmarshalJSON 函数
猜你喜欢
  • 1970-01-01
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 2020-05-02
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多