Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through PyMongo Cursor as key-value pair

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
like image 200
Uyghur Lives Matter Avatar asked Feb 08 '11 00:02

Uyghur Lives Matter


People also ask

How does Pymongo cursor work?

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.

What does find() return in PyMongo?

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.

How can I tell if Pymongo cursor is empty?

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.

How to iterate MongoDB collection in Python?

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.


1 Answers

Try:

records = dict((record['_id'], record) for record in cursor)
like image 187
Spike Gronim Avatar answered Oct 14 '22 15:10

Spike Gronim