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

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

我想获取MongoDB集合中所有键的名称。
例如,从这个:

  1. "Id": ObjectId("5f5a010d431c4519dcda0e3d")
  2. "title": "App"
  3. "query": ""
  4. "db": ""
  5. "widgettype": ""
  6. "tablename": "active_instance"
  7. fields:Object
  8. user:"name",
  9. key:"passcode"
  10. "status": "active"
  11. "inlibrary": ""
  12. "createdts": 1599733804

字符串

使用“gopkg.in/mgo.v2“和“gopkg.in/mgo.v2/bson“包

  1. err := mongodbSession.DB(dbName).C(collectionName).Find(bson.M{}).One(&result)
  2. var keyset []string
  3. for index, _ := range result {
  4. fmt.Printf("%+v\n", index)
  5. keyset = append(keyset, index)
  6. }
  7. fmt.Println(keyset)


输出如下

  1. [_id title query db widgettype status fields inlibrary createdts ]

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

ymdaylpp

ymdaylpp1#

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

  1. func getKeys(m bson.M) (keys []string) {
  2. for k, v := range m {
  3. keys = append(keys, k)
  4. if m2, ok := v.(bson.M); ok {
  5. keys = append(keys, getKeys(m2)...)
  6. }
  7. }
  8. return
  9. }

字符串
使用它的示例:

  1. m := bson.M{"Id": bson.ObjectId("5f5a010d431c4519dcda0e3d"),
  2. "title": "App",
  3. "query": "",
  4. "db": "",
  5. "widgettype": "",
  6. "tablename": "active_instance",
  7. "fields": bson.M{
  8. "user": "name",
  9. "key": "passcode",
  10. },
  11. "status": "active",
  12. "inlibrary": "",
  13. "createdts": 1599733804,
  14. }
  15. keys := getKeys(m)
  16. fmt.Println(keys)


这将输出(在Go Playground上尝试):

  1. [db widgettype createdts inlibrary _id title query tablename
  2. fields user key status]


如果您查看结果,则会发现userkey包含在内,但无法分辨它们是文档的字段还是嵌入文档的字段。
您可以选择将嵌入文档字段本身的字段名称作为嵌入文档字段的前缀,例如获取fields.userfields.key
这是你可以做到这一点:

  1. func getKeys(m bson.M) (keys []string) {
  2. for k, v := range m {
  3. keys = append(keys, k)
  4. if m2, ok := v.(bson.M); ok {
  5. for _, k2 := range getKeys(m2) {
  6. keys = append(keys, k+"."+k2)
  7. }
  8. }
  9. }
  10. return
  11. }


这将输出(在Go Playground上尝试):

  1. [createdts title query db status inlibrary _id widgettype tablename
  2. 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

  1. {"fields": {
  2. "user": "alex",
  3. "nickname": "ferguson",
  4. }}

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

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "time"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/mongo"
  9. "go.mongodb.org/mongo-driver/mongo/options"
  10. )
  11. func main() {
  12. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  13. defer cancel()
  14. client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
  15. if err != nil {
  16. log.Panicln(err)
  17. }
  18. defer client.Disconnect(ctx)
  19. var docRaw bson.Raw
  20. res := client.Database("store").Collection("users").FindOne(context.Background(), bson.D{})
  21. err = res.Decode(&docRaw)
  22. if err != nil {
  23. log.Panicln(err)
  24. }
  25. elements, err := docRaw.Elements()
  26. if err != nil {
  27. log.Panicln(err)
  28. }
  29. var keys []string
  30. for _, e := range elements {
  31. keys = append(keys, getKey(e)...)
  32. }
  33. fmt.Println(keys)
  34. }
  35. func getKey(e bson.RawElement) []string {
  36. if e.Value().Type != bson.TypeEmbeddedDocument {
  37. return []string{e.Key()}
  38. }
  39. var result []string
  40. nested, _ := e.Value().Document().Elements()
  41. for _, n := range nested {
  42. nKeys := getKey(n)
  43. for _, k := range nKeys {
  44. result = append(result, fmt.Sprintf("%s.%s", e.Key(), k))
  45. }
  46. }
  47. return result
  48. }


输出量:

  1. [_id fields.user fields.nickname]

展开查看全部

相关问题