json - 将一个 mongodb 对象数组转储到一个结构片段中

标签 json mongodb go mongo-go

我在 mongodb 文档中有一个对象数组以及其他字段:

db.config.find({},{list_attributes:1, _id:0});
[
{
    list_attributes: {
    '0': { field: 'LASTNAME', field_key: 'lastname', dataType: 'text' },
    '1': { field: 'FIRSTNAME', field_key: 'firstname', dataType: 'text' },
    '2': { field: 'SMS', dataType: 'text' },
    '3': {
        field: 'DOUBLE_OPT-IN',
        dataType: 'category',
        order: 1,
        catAttrib: { '1': 'Yes', '2': 'No' }
    },
    '4': { field: 'OPT_IN', dataType: 'boolean', order: 2 },
    '5': { field: 'TEST_NUMBER', dataType: 'float', order: 3 },
    '6': { field: 'TEST_DATE', dataType: 'date', order: 4 }
    }
}
]

我想将此数据转储到以下结构的 slice 中,以便 slice 的第 0 个索引包含 list_attributes 数组的第 0 个对象:

type MongoFields struct {
    Field     string `bson:"field" json:"field"`
    FieldKey  string `bson:"field_key,omitempty" json:"field_key,omitempty"`
    DataType  string `bson:"data_type" json:"data_type"`
    Order     int    `bson:"order,omitempty" json:"order,omitempty"`
    CatAttrib bson.M `bson:"catAttrib,omitempty" json:"catAttrib,omitempty"`
}

我使用的是 golang 的官方 mongodb 驱动。

package main

import (
    "context"       // manage multiple requests
    "encoding/json" // Use JSON encoding for bson.M string
    "fmt"           // Println() function
    "log"
    "reflect" // get an object type

    // import 'mongo-go-driver' package libraries
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type MongoFields struct {
    Field     string `bson:"field" json:"field"`
    FieldKey  string `bson:"field_key,omitempty" json:"field_key,omitempty"`
    DataType  string `bson:"data_type" json:"data_type"`
    Order     int    `bson:"order,omitempty" json:"order,omitempty"`
    CatAttrib bson.M `bson:"catAttrib,omitempty" json:"catAttrib,omitempty"`
}

func main() {

    // Declare host and port options to pass to the Connect() method
    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")

    // Connect to the MongoDB and return Client instance
    client, err := mongo.Connect(context.TODO(), clientOptions)
    if err != nil {
        fmt.Println("mongo.Connect() ERROR:", err)
        log.Fatal(err)
    }

    // Declare Context object for the MongoDB API calls
    ctx := context.Background()

    // Access a MongoDB collection through a database
    col := client.Database("SomeDatabase").Collection("Some Collection")

    // Typical BSON Map filter
    //filter := bson.M{"int field": bson.M{"$gt":42}}

    // Create a string using ` string escape ticks
    query := `{list_attributes:1, _id:0}`

    // Declare an empty BSON Map object
    var bsonMap bson.M

    // Use the JSON package's Unmarshal() method
    err = json.Unmarshal([]byte(query), &bsonMap)
    if err != nil {
        panic(err)
    } else {
        fmt.Println("bsonMap:", bsonMap)
        fmt.Println("bsonMap TYPE:", reflect.TypeOf(bsonMap))
    }

    // Nest the Unmarshalled BSON map inside another BSON object
    filter := bson.M{"field": bsonMap}

    // Pass the filter to Find() to return a MongoDB cursor
    cursor, err := col.Find(ctx, filter)
    if err != nil {
        log.Fatal("col.Find ERROR:", err)
    }

    // Print cursor object
    fmt.Println("\ncursor TYPE:", reflect.TypeOf(cursor))
    fmt.Println("cursor:", cursor)

    // iterate through all documents
    for cursor.Next(ctx) {
        var p MongoFields

        // Decode the document
        if err := cursor.Decode(&p); err != nil {
            log.Fatal("cursor.Decode ERROR:", err)
        }
        // Print the results of the iterated cursor object
        fmt.Printf("\nMongoFields: %+v\n", p)
    }
}

我得到:

panic: invalid character 'l' looking for beginning of object key string

goroutine 1 [running]:
main.main()
    /home/arun/GolandProjects/storeInSlice/main.go:54 +0x6c5

最佳答案

您的查询 JSON 不是有效的 JSON:

// Create a string using ` string escape ticks
query := `{list_attributes:1, _id:0}`

// Declare an empty BSON Map object
var bsonMap bson.M

// Use the JSON package's Unmarshal() method
err = json.Unmarshal([]byte(query), &bsonMap)

一个有效的 JSON 应该是:

query := `{"list_attributes":1, "_id":0}`

但是使用复合文字来创建这样的投影要简单得多:

query := bson.M{
    "list_attributes": 1,
    "_id":             0,
}

这是一个定义投影的文档(列出您要检索的字段)。这不应与过滤器文档相同。

要在没有过滤器的情况下获取所有文档,请使用空文档,例如:

filter := bson.D{}
// or 
filter := bson.M{}

关于json - 将一个 mongodb 对象数组转储到一个结构片段中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72950009/

相关文章:

javascript - 我在将 hashMap String 发送到服务器 php 时遇到问题,而不是在 volley 响应 android 中返回 JsonArray

ios - AFNetworking v3.1.0 multipartFormRequestWithMethod 上传带引号的 JSON 数值

mongodb - 蒙戈数据库 : $lookup (aggregation)/join with two different data types

sockets - Golang 原始套接字丢失数据包?

javascript - 如何使用javascript将大型json文件拆分为多个小块文件以显示在谷歌地图中

json - 如何从 DataContract 中排除类型信息?

MongoDB - 搜索文本

mongodb - 如何用MongoDB(Motor)实现FastAPI的pytest

http - Golang HTTP 和文件缓存

authentication - 如何在访问 Google App 的多个服务之间共享凭据