Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve data from pymongo

Tags:

python

mongodb

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.

like image 346
snake plissken Avatar asked May 07 '14 10:05

snake plissken


People also ask

How do I get data from 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. In this example we use an empty query object, which selects all documents in the collection.

How retrieve data from MongoDB?

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.

How do I get all files in collection PyMongo?

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.

What does Find_one return PyMongo?

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.


1 Answers

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']
like image 183
msvalkon Avatar answered Oct 17 '22 00:10

msvalkon