如何将非字符串对象作为数据库中的键插入

时间:2018-05-09 07:38:31

标签: python mongodb key

现在我正在使用 mongoDB ,并且仅根据数据类型限制面对基本错误“”。

  

InvalidDocument:文档必须只有字符串键,键是('好','有益')

我尝试过的行动如下:

1)创建一个名为'glot'

的数据库

2)制作一个名为“usr_history”的集合

3)尝试将usr_history文档插入集合

在jupyter-notebook中使用以下命令

import pymongo

from pymongo import MongoClient

client = MongoClient() #to run the mongod instance we need a client to run it

db = client['glot'] #we connect to 'test-database' with the pre-defined client instance

collection = db['usr_history']

edge_attr = {('good','beneficial'):"good is beneficial", ('beneficial','supportive'):"beneficial means something supportive"} #create this with glat_algo

usr_history = {"nodes": ['good', 'beneficial', 'supportive'], "edges": [('good', 'beneficial'), ('beneficial', 'supportive')], "rephrase": edge_attr}

collection.insert_one(usr_history)

,最后一个命令返回错误,如上所述。

基本上我要做的是将(vertex,edge,edge_attr)数据存储到任何数据库中,这样我就可以跟踪大量的usr_history数据,以便使用python进行分析。

我不仅限于mongoDB,所以你可以给我一个指南或解决方案,不仅可以使用mongoDB,还可以使用其他替代方案。

非常感谢你。

1 个答案:

答案 0 :(得分:0)

您不能使用非字符串值作为键;只有字符串可以是键。

如果将('good','beneficial')存储为单独属性的值,它会更好用,可能是这样的:

edge_attr = [
  {"attr" : ('good','beneficial'), "val" : "good is beneficial"}, 
  {"attr" : ('beneficial','supportive'), "val" : "beneficial means something supportive"}
];
相关问题