Bobby
Bobby

Reputation: 4512

Python MongoDB Dict Results?

Is there away to retrieve results from MongoDB in Python using PyMongo and have them in dict style? For example

    clogin = self.mdb.database.users.find_one( {"$and": [{"username" : str(username)},  {"password" : newpass}]})
    fname = clogin['First_name']

Upvotes: 0

Views: 4686

Answers (2)

César
César

Reputation: 10119

According to pymongo 2.0 documentation:

The most basic type of query that can be performed in MongoDB is find_one(). This method returns a single document matching a query (or None if there are no matches). It is useful when you know there is only one matching document, or are only interested in the first match. Here we use find_one() to get the first document from the posts collection:

>>> posts.find_one()
{u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}

The result is a dictionary matching the one that we inserted previously.

Upvotes: 2

sojin
sojin

Reputation: 4694

What you are doing would give you Dict Results. find_one() by pymongo returns results as dictionary. You may use clogin.get('First_name') to get result if exists or default to None if not.

find() would return a cursor so you might want to iterate over and get the results in the way you need.

Upvotes: 1

Related Questions