使用Go获取集合中所有键的名称

j9per5c4  于 2023-11-14  发布在  Go
关注(0)|答案(2)|浏览(82)

我想获取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 ]

子密钥未被提供,即用户和密钥

ymdaylpp

ymdaylpp1#

嵌入的文档将显示为result中的另一个bson.M值,因此您必须使用递归来遍历这些值。
你可以这样做:

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]


如果您查看结果,则会发现userkey包含在内,但无法分辨它们是文档的字段还是嵌入文档的字段。
您可以选择将嵌入文档字段本身的字段名称作为嵌入文档字段的前缀,例如获取fields.userfields.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]


还要注意,上面的解决方案不处理数组。如果你有数组,你也应该递归地覆盖它们,如果它们包含另一个数组或对象,你也应该做同样的事情(递归地)。这是一个练习,你可以扩展它来处理数组。

uxhixvfz

uxhixvfz2#

包“gopkg.in/mgo.v2“和“gopkg.in/mgo.v2/bson“已过时。请替换为“go.mongodb.org/mongo-driver/bson“和“go.mongodb.org/mongo-driver/mongo“。必须使用递归来检索嵌套字段。假定数据库“store”具有包含此文档的集合“users

{"fields": {
  "user": "alex",
  "nickname": "ferguson",
}}

字符串
从集合中检索键的代码是:

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
    defer cancel()
    client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))

    if err != nil {
        log.Panicln(err)
    }
    defer client.Disconnect(ctx)
    var docRaw bson.Raw
    res := client.Database("store").Collection("users").FindOne(context.Background(), bson.D{})

    err = res.Decode(&docRaw)
    if err != nil {
        log.Panicln(err)

    }
    elements, err := docRaw.Elements()
    if err != nil {
        log.Panicln(err)
    }
    var keys []string
    for _, e := range elements {
        keys = append(keys, getKey(e)...)
    }
    fmt.Println(keys)
}

func getKey(e bson.RawElement) []string {
    if e.Value().Type != bson.TypeEmbeddedDocument {
        return []string{e.Key()}
    }
    var result []string
    nested, _ := e.Value().Document().Elements()
    for _, n := range nested {
        nKeys := getKey(n)
        for _, k := range nKeys {
            result = append(result, fmt.Sprintf("%s.%s", e.Key(), k))
        }
    }
    return result
}


输出量:

[_id fields.user fields.nickname]

相关问题