如何使用python(pymongo)将嵌套文档插入到mongodb中



我想使用 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'
}
]
}

我自己试过了。代码如下。

从皮蒙戈进口蒙戈客户端

尝试: conn = MongoClient(( 打印("连接成功!!"( except:
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) 

打印("使用记录 ID 插入的数据",rec_id1(

打印插入的数据

cursor = collection.find()
for record in cursor: 
print(record) 

但它显示以下错误:

File "emo.py", line 20
'home' : {
^
syntax error : invalid syntax'

我明白了。 我缺少牙套。我在下面进行了更改。

{
'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'
}
}]
}

MongoDB是一个非关系数据库,你可以以JSON格式存储任何模式的文档。

conn = pymongo.MongoClient('localhost')  # replace localhost with the real address
db = conn['db_name']
db['collection_name'].insert_one({'x': 1})  # replace {'x': 1} with `customer`

http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one

最新更新