简体   繁体   中英

How to insert nested documents in to mongodb using python (pymongo)

I want to insert nested lists/documents in to mongodb using python/pymongo. I want to insert the following in to mongodb using python. can somebody help?

customer =

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

I had tried myself. the code is as below.

from pymongo import MongoClient

try: conn = MongoClient() print("Connected successfully!!!") except:
print("Could not connect to MongoDB")

database

db = conn.database 

Created or Switched to collection names: 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'
    }
  ]
}

Insert Data

rec_id1 = collection.insert(customer) 

print("Data inserted with record ids",rec_id1)

Printing the data inserted

cursor = collection.find()

for record in cursor: 
    print(record) 

but it shows following error:

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

MongoDB is a non-relational database, you can store the document with any schema in JSON format.

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

I got it. I was missing braces.I have made changes below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM