我有一个对象数组以及 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 关注
- 101 浏览
添加回答
举报
0/150
提交
取消