我有一個對象數組以及 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 } }}]我想將此數據轉儲到以下結構的切片中,以便切片的第 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 驅動程序。panic: invalid character 'l' looking for beginning of object key stringgoroutine 1 [running]:main.main() /home/arun/GolandProjects/storeInSlice/main.go:54 +0x6c5
1 回答

揚帆大魚
TA貢獻1799條經驗 獲得超9個贊
您的查詢 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{}
- 1 回答
- 0 關注
- 92 瀏覽
添加回答
舉報
0/150
提交
取消