Reputation: 2665
I am very new to MongoDB and using jupyter notebook for extracting data from mongodb. I am trying to fetch first 100 documents in MongoDB and i do have a crude way of fetching only 100 documents which is to add a counter and stop at 100th counter.
#import library
import pymongo
from pymongo import MongoClient
#connect with mongo client
client = MongoClient('myipaddress', 27011)
db = client.mydatabase_test
collection = db.mycollection_in_testdatabase
#start counter
i=0
for obj in collection.find():
if i <= 100:
print obj['dummy_column']
i = i+1
else:
break
Is there any better way to do this in mongodb? I am sure there must be some equivalent of select * from mydb limit 100
in mongodb. Can anyone help?
Upvotes: 1
Views: 2630
Reputation: 3930
As Yogesh said , you should use limit.
e.g.
cursor = collection.find().limit(100)
Now that you have created cursor you can extract some field like this:
something = [] # list for storing your 100 values of field dummy_column
for doc in cursor: # loop through these 100 entries
something.append(doc.get('dummy_column', '')) # append to this list vallue of field **dummy_column**
Upvotes: 2