Is it possible to iterate over a pymongo Cursor
as a key-value pair like a dict
? I'm using python 2.6 and pymongo 1.9.
I've tried this:
import pymongo
mongo = pymongo.Connection('localhost')
mongo_db = mongo['my_database']
mongo_coll = mongo_db['my_collection']
cursor = mongo_coll.find()
records = dict([(record_id, record) for record_id, record in mongo_cursor])
But I get the error:
ValueError: too many values to unpack
collection. find() to search documents in collections then as a result it returns a pointer. That pointer is known as a cursor. Consider if we have 2 documents in our collection, then the cursor object will point to the first document and then iterate through all documents which are present in our collection.
To select data from a table in MongoDB, we can also use the find() method. The find() method returns all occurrences in the selection. The first parameter of the find() method is a query object.
Check if the Cursor object is empty or not? Approach 1: The cursor returned is an iterable, thus we can convert it into a list. If the length of the list is zero (i.e. List is empty), this implies the cursor is empty as well.
Find a MongoDB document in Python using the find_one() method. The MongoDB find_one() method in Python can be used to iterate the documents in a MongoDB collection, returning the first document that it encounters. Unlike the find() method that we discussed earlier, find_one() does not return a pymongo.
Try:
records = dict((record['_id'], record) for record in cursor)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With