Python MongoDB LIMIT

  • 限制结果

    为了限制MongoDB中的结果,我们使用limit()方法。limit()方法采用一个参数,一个数字定义要返回的文档数。假设您有一个“customers”集合:
    {'_id': ObjectId('5e13e538eb09ef0118b00093'), 'name': 'John', 'address': 'Highway 37'} 
    {'_id': ObjectId('5e13e56c383d47cc7eaeb561'), 'name': 'Peter', 'address': 'Lowstreet 27'} 
    {'_id': ObjectId('5e13e58628aa57f77766565c'), 'name': 'Amy', 'address': 'Apple st 652'} 
    {'_id': ObjectId('5e13e58628aa57f77766565d'), 'name': 'Hannah', 'address': 'Mountain 21'} 
    {'_id': ObjectId('5e13e58628aa57f77766565e'), 'name': 'Michael', 'address': 'Valley 345'} 
    {'_id': ObjectId('5e13e58628aa57f77766565f'), 'name': 'Sandy', 'address': 'Ocean blvd 2'} 
    {'_id': ObjectId('5e13e58628aa57f777665660'), 'name': 'Betty', 'address': 'Green Grass 1'} 
    {'_id': ObjectId('5e13e58628aa57f777665661'), 'name': 'Richard', 'address': 'Sky st 331'} 
    {'_id': ObjectId('5e13e58628aa57f777665662'), 'name': 'Susan', 'address': 'One way 98'} 
    {'_id': ObjectId('5e13e58628aa57f777665663'), 'name': 'Vicky', 'address': 'Yellow Garden 2'} 
    {'_id': ObjectId('5e13e58628aa57f777665664'), 'name': 'Ben', 'address': 'Park Lane 38'} 
    {'_id': ObjectId('5e13e58628aa57f777665665'), 'name': 'William', 'address': 'Central st 954'} 
    {'_id': ObjectId('5e13e58628aa57f777665666'), 'name': 'Chuck', 'address': 'Main Road 989'} 
    {'_id': ObjectId('5e13e58628aa57f777665667'), 'name': 'Viola', 'address': 'Sideway 1633'} 
    {'_id': 1, 'name': 'John', 'address': 'Highway 37'} 
    {'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'} 
    {'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'} 
    {'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'} 
    {'_id': 5, 'name': 'Michael', 'address': 'Valley 345'} 
    {'_id': 6, 'name': 'Sandy', 'address': 'Ocean blvd 2'} 
    {'_id': 7, 'name': 'Betty', 'address': 'Green Grass 1'} 
    {'_id': 8, 'name': 'Richard', 'address': 'Sky st 331'} 
    {'_id': 9, 'name': 'Susan', 'address': 'One way 98'} 
    {'_id': 10, 'name': 'Vicky', 'address': 'Yellow Garden 2'} 
    {'_id': 11, 'name': 'Ben', 'address': 'Park Lane 38'} 
    {'_id': 12, 'name': 'William', 'address': 'Central st 954'} 
    {'_id': 13, 'name': 'Chuck', 'address': 'Main Road 989'} 
    {'_id': 14, 'name': 'Viola', 'address': 'Sideway 1633'} 
    
  • 将结果限制为仅返回5个文档:

    import pymongo
    
    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient["mydatabase"]
    mycol = mydb["customers"]
    
    myresult = mycol.find().limit(5)
    
    #print the result:
    for x in myresult:
      print(x)
    
    尝试一下