【发布时间】: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.1和WanDevice.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