select * 使用 pymongo 在 MongoDB 中限制 100 等价物

select * limit 100 equivalent in MongoDB using pymongo

我对 MongoDB 很陌生,使用 jupyter notebook 从 mongodb 中提取数据。我正在尝试获取 MongoDB 中的前 100 个文档,我确实有一种粗略的方法可以只获取 100 个文档,即添加一个计数器并在第 100 个计数器停止。

#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

在 mongodb 中有更好的方法吗?我确信 mongodb 中一定有一些等同于 select * from mydb limit 100 的东西。有人可以帮忙吗?

正如 Yogesh 所说,您应该使用 limit
例如

cursor = collection.find().limit(100)

现在您已经创建了 游标,您可以像这样提取一些字段:

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**