I ve got a mongo database and I want to retrieve all documents with a cursor operation like in mongodb java api. I want to retrieve all username of database based on this cursor iteration. My code is like the above:
import pymongo
from pymongo import MongoClient
client = MongoClient('...', 27017)
db = client.test_database
db = client['...']
collection = db.test_collection
collection = db["..."]
result = collection.find()
obj = next(result, None)
if obj:
username= obj['username']
print username
I want for the collection to print all the usernames.
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. In this example we use an empty query object, which selects all documents in the collection.
You can use read operations to retrieve data from your MongoDB database. There are multiple types of read operations that access the data in different ways. If you want to request results based on a set of criteria from the existing set of data, you can use a find operation such as the find() or findOne() methods.
To get all the Documents of the Collection use find() method. The find() method takes a query object as a parameter if we want to find all documents then pass none in the find() method.
The find_One() method of pymongo is used to retrieve a single document based on your query, in case of no matches this method returns nothing and if you doesn't use any query it returns the first document of the collection.
Just loop over the results and print the username
. There's no reason to play with next()
.
for obj in collection.find():
print obj['username']
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