Reputation: 778
What is best way to extract all _id from mongodb collection? I am using pymongo to work with mongodb. Following code:
for item in db.some_collection.find({}, {'_id': 1}):
# do something
takes some time to iterate over all collection. I need only _id values and they all should fit in memory. Why does this code not complete immediately?
Upvotes: 4
Views: 1659
Reputation: 62908
Use distinct
:
some_collection.distinct('_id')
In [5]: c = pymongo.connection.Connection('127.0.0.1')
In [6]: c['test']['test'].insert({'a': 2})
Out[6]: ObjectId('5159c8e9d286da0efccb7b70')
In [7]: c['test']['test'].insert({'a': 3})
Out[7]: ObjectId('5159c8ecd286da0efccb7b71')
In [8]: c['test']['test'].insert({'a': 5})
Out[8]: ObjectId('5159c8edd286da0efccb7b72')
In [9]: c['test']['test'].distinct('_id')
Out[9]:
[ObjectId('5159c8e9d286da0efccb7b70'),
ObjectId('5159c8ecd286da0efccb7b71'),
ObjectId('5159c8edd286da0efccb7b72')]
Upvotes: 7