英文:
Need help to storing an map of type interface in my mongodb database using golang
问题
我正在创建一个应用程序,其中后端使用Go语言,数据库使用MongoDB。我的问题是,我在结构体中声明了一个map,像这样:
Data struct {
data map[interface{}]interface{}
}
在添加值之后,像这样:
var data Data
data["us"]="country"
data[2]="number"
data["mother"]="son"
我像这样插入它:
c.Insert(&data)
当我插入后,我丢失了键,只能看到值...
{
"_id" : Object Id("57e8d9048c1c6f751ccfaf50"),
"data" : {
"<interface {} Value>" : "country",
"<interface {} Value>" : "number",
"<interface {} Value>" : "son"
},
}
请问有没有办法在MongoDB中使用接口来获取键和值?谢谢...
英文:
I m in the process of creating application where my back end is in go lang and database is mongoDB. My problem is that i have a map in my struct declared like
Data struct {
data map[interface{}]interface{}
}
after adding values in to this like
var data Data
data["us"]="country"
data[2]="number"
data["mother"]="son"
I m inserting it like
c.Insert(&data)
When i insert this i m losing my key and can only see the values...
{
"_id" : Object Id("57e8d9048c1c6f751ccfaf50"),
"data" : {
"<interface {} Value>" : "country",
"<interface {} Value>" : "number",
"<interface {} Value>" : "son"
},
}
May i know any way possible to use interface and get both key and values in my mongoDB. Thanks....
答案1
得分: 3
在MongoDB文档中,你只能使用string
作为键。即使你将Data
结构定义为map[int]interface{}
,MongoDB(不知道mgo
是否会转换类型)也不允许你将该对象插入数据库。实际上,你在JSON中只能使用string
作为键,因为这不是有效的JSON(在浏览器控制台中尝试运行以下代码JSON.parse('{2:"number"}')
)。
因此,将你的Data
定义为bson.M
(map[string]interface{}
的快捷方式),并使用strconv
包将数字转换为字符串。
但我猜你可能需要考虑数组/切片,因为将数字作为JSON键的唯一原因是以后需要通过这些字段进行迭代。而对于迭代,我们使用数组。
更新:刚刚检查了mgo
如何处理map[int]interface{}
。它将其插入数据库条目中,格式为{"<int Value>": "hello"}
。其中<int Value>
不是数字,而是实际的string <int Value>
英文:
You can use nothing but string
as key in MongoDB documents. Even if you would define your Data
structure as map[int]interface{}
Mongo (don't know if mgo
will convert types) wouldn't allow you to insert this object into the database. Actually, you can use nothing but string
as JSON key at all as this wouldn't be JSON (try in your browser console the next code JSON.parse('{2:"number"}')
).
So define your Data
as bson.M
(shortcut for map[string]interface{}
) and use strconv
package to convert your numbers into strings.
But I guess you must look at arrays/slices, as only one reason why someone may need to have numbers as keys in JSON is iterations through these fields in future. And for iterations we use arrays.
Update: just checked how mgo
deals with map[int]interface{}
. It inserts into DB entry like {"<int Value>" : "hello"}
. Where <int Value>
is not number but actually string <int Value>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论