1

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" : "[email protected]", "mobile" : "78978555", "name" : "rohit" }
{ "_id" : ObjectId("513f2cfeae4cb53c1374b4f7"), "username" : "[email protected]", "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 .

1
  • what is get when you print it? Commented Mar 12, 2013 at 14:09

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

4 Comments

thanks it is working for me .But what if i want to check only for single record. Should i do the same for FindOne also ?
find_one returns a dict, so then you don't have to iterate but can directly address it: x = find_one({'name': your_name}) then print x['name']
last thing what if there is no matching query it returns None or what?
try it. find will return an empty iterator. find_one will return None
1

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.

1 Comment

Above query will also work print(element.name) instead of print(get.name)

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.