如何使用PyMongo在对象中插入多个字典值

时间:2018-11-02 22:38:22

标签: python mongodb pymongo

from pymongo import MongoClient

#Step 1: Connect to MongoDB - Note: Change connection string as needed
client = MongoClient(port=27017)
db=client.cltest
#Step 2: Create sample data
names = ['Kitchen','Animal','State', 'Tasty']
company_type = ['LLC','Inc','Company','Corporation']
company_cuisine = ['Pizza', 'Bar Food', 'Fast Food', 'Italian']


# Change Names List into Dictionary Format to Insert into MongoDB
namesdict = {}
namesrange = len(names)
for x in range(0, namesrange):
    if names[x] in namesdict:
        continue
    else:
        namesdict['names'] = names[x]

    #Step 3: Insert namesdict object directly into MongoDB via insert_one
result=db.reviews1.insert_many(namesdict)
    #Step 4: Print to the console the ObjectID of the new document
print('Created {0}'.format(result.inserted_id))

TypeError:文档必须是dict,bson.son.SON,bson.raw_bson.RawBSONDocument的实例,或者是从collections.MutableMapping继承的类型

我是Pymongo和Python的新手,所以不确定是否可行。

我的目标是获取具有从列表中编译的几个不同值的Dictionary,然后使用namesdict的字典对象将这些值插入MongoDB。我知道我可以手动写出每个字典值,然后插入它们,但是正在寻找一种更有效的方法。希望有一种方法可以从数组对象中一次插入许多对象。

数据库结构类似于以下内容:
cltest(DB)
reviews1(文档)
字段(_id ObjectId,名称)
列(名称)
厨房(值)
动物(值)
状态(值)
美味(价值)

更新1

dic1 = {'website': 'www.carrefax.com'}, {'website': 'Daniel Hoadley'}, {'website': 'purple'}

for item in dic1:
    collection.insert_one(item)

上面的代码使我可以在数据库中输入多个条目。我仍然遇到问题的地方是将list(name)转换成字典,例如dic1,其中所有键都相同。

更新2-找到了一个解决方案,用于将单个导入量列表导入MongoDB

更新3
现在,我尝试将所有三个列表转换为字典。然后将所有其他列表中的数据插入每个名称项,以使名字的顺序与第一个公司类型相对应,第一个公司类型也与第一个公司美食条目相对应,依此类推。

更新代码:

from pymongo import MongoClient

# Create connection to MongoDB
client = MongoClient('localhost', 27017)
db = client['name_of_database']
collection = db['name_of_collection']
names = ['Kitchen','Animal','State', 'Tasty']
company_type = ['LLC','Inc','Company','Corporation']
company_cuisine = ['Pizza', 'Bar Food', 'Fast Food', 'Italian']

# Build a basic dictionary & Insert into DB
for item in names:
    data = {}

    data['name'] = item
    collection.insert_one(data)

for item in company_type:
    data = {}

    data['company_type'] = item
    collection.insert_one(data)

for item in company_cuisine:
    data = {}

    data['cuisine'] = item
    collection.insert_one(data)


更新4-已解决

from pymongo import MongoClient

# Create connection to MongoDB
client = MongoClient('localhost', 27017)
db = client['name_of_database']
collection = db['name_of_collection']
names = ['Kitchen','Animal','State', 'Tasty']
company_type = ['LLC','Inc','Company','Corporation']
company_cuisine = ['Pizza', 'Bar Food', 'Fast Food', 'Italian']

# Build a basic dictionary & Insert into DB

for i, c, p in zip(names, company_type, company_cuisine):
    data = {}
    data['name'] = i
    data['company_type'] = c
    data['cuisine'] = p
    collection.insert_one(data)

0 个答案:

没有答案