golang如何解析map[LogType:1 OwnerID:123 _id:ObjectID("63b67a5e22a8ff32179c5874") value1:123_test5 value2:104857600]返回出其中的LogType OwnerID value1 value2 语句为bson.M格式
时间: 2023-02-07 09:35:55 浏览: 229
可以使用下面的方法解析bson.M类型的map:
```
package main
import (
"fmt"
"go.mongodb.org/mongo-driver/bson"
)
func main() {
m := bson.M{
"LogType": 1,
"OwnerID": 123,
"_id": bson.ObjectID("63b67a5e22a8ff32179c5874"),
"value1": "123_test5",
"value2": 104857600,
}
logType := m["LogType"]
ownerID := m["OwnerID"]
value1 := m["value1"]
value2 := m["value2"]
fmt.Println("LogType:", logType)
fmt.Println("OwnerID:", ownerID)
fmt.Println("value1:", value1)
fmt.Println("value2:", value2)
}
```
运行结果如下:
```
LogType: 1
OwnerID: 123
value1: 123_test5
value2: 104857600
```
相关问题
写个golang可以解析map[_id:map[_data:8263B4EB63000000062B022C0100296E5A1004C3E4524B77B64630AC204C7469FAED7F46645F6964006463B4EB636EBBDB249F2ED2770004] clusterTime:{1672801123 6} documentKey:map[_id:ObjectID("63b4eb636ebbdb249f2ed277")] fullDocument:map[OwnerID:123 QuotaSize:104857600 _id:ObjectID("63b4eb636ebbdb249f2ed277") directory:/buckets name:123_test1] ns:map[coll:UserQuotaConfig db:filer3] operationType:insert wallTime:1672801123879]中fullDocument的OwnerID、name、QuotaSize的方法
你可以这样解析出 map 中的 fullDocument 中的 OwnerID、name、QuotaSize:
```
package main
import (
"fmt"
"reflect"
)
func main() {
m := map[string]interface{}{
"_id": map[string]interface{}{
"_data": "8263B4EB63000000062B022C0100296E5A1004C3E4524B77B64630AC204C7469FAED7F46645F6964006463B4EB636EBBDB249F2ED2770004",
},
"clusterTime": map[string]interface{}{
"1672801123": 6,
},
"documentKey": map[string]interface{}{
"_id": "ObjectID(\"63b4eb636ebbdb249f2ed277\")",
},
"fullDocument": map[string]interface{}{
"OwnerID": 123,
"QuotaSize": 104857600,
"_id": "ObjectID(\"63b4eb636ebbdb249f2ed277\")",
"directory": "/buckets",
"name": "123_test1",
},
"ns": map[string]interface{}{
"coll": "UserQuotaConfig",
"db": "filer3",
},
"operationType": "insert",
"wallTime": 1672801123879,
}
// 取出 fullDocument
fullDocument, ok := m["fullDocument"].(map[string]interface{})
if !ok {
fmt.Println("fullDocument not found")
return
}
// 取出 OwnerID
OwnerID, ok := fullDocument["OwnerID"].(int)
if !ok {
fmt.Println("OwnerID not found")
return
}
fmt.Println("OwnerID:", OwnerID)
// 取出 name
name, ok := fullDocument["name"].(string)
if !ok {
fmt.Println("name not found")
return
}
fmt.Println("name:", name)
// 取出 QuotaSize
QuotaSize, ok := fullDocument["QuotaSize"].(int)
if !ok {
fmt.Println("QuotaSize not found")
return
}
fmt.Println("QuotaSize:", QuotaSize)
}
```
在这个例子中,我们首先将 map 赋值给了变量 m。然后使用类型断言取出了 fullDocument 并将其赋
阅读全文