2

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'
0

2 Answers 2

3

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'
  }
 }]
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

i am getting the same error as i have mentioned above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.