user977828
user977828

Reputation: 7679

How to get a list of _id names in PyMongo

I would like to create a list of _id names e.g. ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] with PyMongo out of this query:

> db.users.find({},{ "_id":1} ).limit(10)
{ "_id" : "0" }
{ "_id" : "1" }
{ "_id" : "2" }
{ "_id" : "3" }
{ "_id" : "4" }
{ "_id" : "5" }
{ "_id" : "6" }
{ "_id" : "7" }
{ "_id" : "8" }
{ "_id" : "9" }

However, the following code does not produces any results:

from pymongo import MongoClient

if __name__ == '__main__':

    db = MongoClient()
    sDB = db.test.users
    for u in list(sDB.users.find({}, {"_id": 1}).limit(10)):
        print "!!!", u

Why is the above list empty?

Upvotes: 0

Views: 300

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

You've referenced into users twice, so it's actually looking in the users.users collection.

This should work (you don't need the list call either):

db = MongoClient()
users = db.test.users
for u in users.find({}, {"_id": 1}).limit(10):
    print "!!!", u

Upvotes: 2

Related Questions