Inputing a String into MongoDB using Pymongo

1.6k views Asked by At

I am trying to get ask the user to input data in to perform the insert, it works whenever I have numbers, but when I input letters it gives me the error "LettersUsed" is not defined. I tried converting the input to str(input('Whatever')) but that did not do the trick any help why it does this?

import pymongo
import sys

#get a connection to database
connection = pymongo.MongoClient('mongodb://localhost')
    #get a handle to database
db=connection.test
vehicles=db.vehicles

vehicle_VIN = input('What is the Vehicle VIN number? ')
vehicle_Make = input('What is the Vehicle Make? ')
newVehicle = {'VIN' : (vehicle_VIN).upper(), 'Make' : (vehicle_Make)}

try:
    vehicles.insert_one(newVehicle)
    print ('New Vehicle Inserted')

except  Exception as e:
        print 'Unexpected error:', type(e), e

#print Results
results = vehicles.find()

print()
# display documents in collection
for record in results:
    print(record['VIN'] + ',',record['Make'])
#close the connection to MongoDB
connection.close()
1

There are 1 answers

2
Martin Konecny On

Message: name 'DAFEQF' is not defined

In Python 2 the code input() is equal to eval(raw_input(prompt)). This means that whatever input you enter, Python2 tries to "evaluate" that input, and will complain that your input is not defined.

Make sure you replace input() with raw_input() (this is only for Python2!)

Replace

vehicle_VIN = input('What is the Vehicle VIN number? ')
vehicle_Make = input('What is the Vehicle Make? ')

with

vehicle_VIN = raw_input('What is the Vehicle VIN number? ')
vehicle_Make = raw_input('What is the Vehicle Make? ')