简体   繁体   中英

Python MongoDB : 'Cursor' object has no attribute 'name'

Just started with mongo db .

context = {}
if request.method == 'POST':
    context['name']  = request.POST['name']
    context['username']  = request.POST['username']
    context['mobile']  = request.POST['mobile']
    get = db.messages.find( { 'name' : request.POST['name'] } )
    if get is not None:
        print get.name

I have two records in my database .

> db.messages.find()
{ "_id" : ObjectId("513f2cf1ae4cb53c1374b4f6"), "username" : "hello@gmail.com", "mobile" : "78978555", "name" : "rohit" }
{ "_id" : ObjectId("513f2cfeae4cb53c1374b4f7"), "username" : "hi@gmail.com", "mobile" : "8528522", "name" : "Rohti" }

when i am posting the form with name rohit . I am getting the above error .

Please tell me what might i am doing wrong here .

I know i am doing wrong query in mongo db .Please help me to get back on track .

get returns as a cursor in pymongo.

try:

for record in get:
    print record['name']

Also, get is not a good name for a variable.

You have to iterate with the cursor:

for element in get:
    print(element.name)

now you are accessing the cursor, which is just a generator of elements and doesn't contain the name directly. See here for a complete explanation.

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