亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Go 獲取集合中所有鍵的名稱

使用 Go 獲取集合中所有鍵的名稱

Go
米脂 2022-07-04 10:07:40
我想獲取 MongoDB 集合中所有鍵的名稱。例如,從此: "Id": ObjectId("5f5a010d431c4519dcda0e3d")            "title": "App"            "query": ""            "db": ""            "widgettype": ""            "tablename": "active_instance"            fields:Object                user:"name",                key:"passcode"            "status": "active"            "inlibrary": ""            "createdts": 1599733804使用“gopkg.in/mgo.v2”和“gopkg.in/mgo.v2/bson”包。err := mongodbSession.DB(dbName).C(collectionName).Find(bson.M{}).One(&result)var keyset []string    for index, _ := range result {        fmt.Printf("%+v\n", index)        keyset = append(keyset, index)    }    fmt.Println(keyset)得到這樣的輸出[_id title query db widgettype  status fields inlibrary createdts ]子密鑰沒有被獲取,即 user 和 key。
查看完整描述

1 回答

?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

嵌入的文檔將bson.M在您的 中顯示為另一個值result,因此您必須使用遞歸來遍歷它們。


您可以這樣做:


func getKeys(m bson.M) (keys []string) {

    for k, v := range m {

        keys = append(keys, k)

        if m2, ok := v.(bson.M); ok {

            keys = append(keys, getKeys(m2)...)

        }

    }

    return

}

使用它的示例:


m := bson.M{"Id": bson.ObjectId("5f5a010d431c4519dcda0e3d"),

    "title":      "App",

    "query":      "",

    "db":         "",

    "widgettype": "",

    "tablename":  "active_instance",

    "fields": bson.M{

        "user": "name",

        "key":  "passcode",

    },

    "status":    "active",

    "inlibrary": "",

    "createdts": 1599733804,

}


keys := getKeys(m)

fmt.Println(keys)

哪個會輸出(在Go Playground上試試):


[db widgettype createdts inlibrary _id title query tablename

  fields user key status]

如果您查看結果user并key包含在內,但無法判斷它們是文檔的字段還是嵌入文檔的字段。


您可以選擇使用嵌入文檔字段本身的字段名稱作為嵌入文檔字段的前綴,例如 getfields.user和fields.key.


您可以這樣做:


func getKeys(m bson.M) (keys []string) {

    for k, v := range m {

        keys = append(keys, k)

        if m2, ok := v.(bson.M); ok {

            for _, k2 := range getKeys(m2) {

                keys = append(keys, k+"."+k2)

            }

        }

    }

    return

}

哪個會輸出(在Go Playground上試試):


[createdts title query db status inlibrary _id widgettype tablename

    fields fields.user fields.key]

另請注意,上述解決方案不處理數組。如果你有數組,你也應該迭代它們,如果它們包含另一個數組或對象,你應該做同樣的事情(遞歸地)。擴展它以處理數組也是一個練習。


查看完整回答
反對 回復 2022-07-04
  • 1 回答
  • 0 關注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號