【发布时间】:2019-02-27 19:57:55
【问题描述】:
我想使用 python/pymongo 将嵌套列表/文档插入到 mongodb。我想使用 python 将以下内容插入到 mongodb 中。有人可以帮忙吗?
客户 =
{
'first_name' : 'Arnold',
'last_name' : 'Pettibone',
'addresses': [
'home' : {
'street' : '1234 fake street',
'city' : 'Anytown',
'state' : 'OH',
'zip' : '12345'
},
'work' : {
'street' : '742 Evergreen Terrace',
'city' : 'Springfield',
'state' : 'OH',
'zip': '12345'
}
]
}
我自己试过了。代码如下。
从 pymongo 导入 MongoClient
尝试:
conn = MongoClient()
print("连接成功!!!")
除了:
print("无法连接到 MongoDB")
数据库
db = conn.database
创建或切换到集合名称:my_collection
collection = db.my_collection
customer = {
'first_name' : 'Arnold',
'last_name' : 'Petti',
'addresses': [
'home' : {
'street' : '1234 fake street',
'city' : 'Anytown',
'state' : 'OH',
'zip' : '12345'
},
'work' : {
'street' : '742 Evergreen Terrace',
'city' : 'Springfield',
'state' : 'OH',
'zip': '12345'
}
]
}
插入数据
rec_id1 = collection.insert(customer)
print("使用记录ID插入的数据",rec_id1)
打印插入的数据
cursor = collection.find()
for record in cursor:
print(record)
但它显示以下错误:
File "emo.py", line 20
'home' : {
^
syntax error : invalid syntax'
【问题讨论】:
标签: python mongodb pymongo-3.x