【问题标题】:How to insert nested documents in to mongodb using python (pymongo)如何使用 python (pymongo) 将嵌套文档插入到 mongodb
【发布时间】: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


    【解决方案1】:

    我明白了。 我缺少大括号。我在下面进行了更改。

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

    【讨论】:

      【解决方案2】:

      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

      【讨论】:

      • 我遇到了与上面提到的相同的错误。
      猜你喜欢
      • 2021-06-10
      • 2015-09-27
      • 2016-05-31
      • 2021-11-30
      • 2015-08-27
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 2018-05-15
      相关资源
      最近更新 更多