Skip to main content
 首页 » 编程设计

python之pymongo 显示 skip 必须是 int 的实例之错误

2024年11月01日9zhujiabin

我是 mongodb 的新手。我想使用 python 从 mongodb 中检索指定日期的某些字段的数据。我的 Mongodb 收藏看起来像这样

{  
    "_id" : ObjectId("5d9d7eec7c6265a42e352d6d"),  
    "browser" : "Chrome",  
    "countryCode" : "IN",  
    "Page" : "http://192.168.1.34/third.html",  
    "date" : "2019-10-09T10:32:08.438660" 
} 
{  
    "_id" : ObjectId("5d9d7eec7c6265a42e352d6e"),  
    "browser" : "Chrome",  
    "countryCode" : "IN",  
    "Page" : "http://192.168.1.14/fourth.html",  
    "date" : "2019-10-12T10:32:08.438662" 
 
 
   } 
 
and so on 

我通过在 mongodb 中使用以下查询从 mongodb 检索数据

db.collection_name.find({"date": {'$gte': "2019-10-09T10:32:08.438660", '$lte': "2019-10-10T10:32:08.438661"}},{}, {Page:[], _id:0}) 

我想在 python 中使用 pymongo 获取该数据。这是我试过的代码,

from pymongo import MongoClient 
import pymongo 
from bson.raw_bson import RawBSONDocument 
 
myclient = pymongo.MongoClient( 
    "mongodb://localhost:27017/", document_class=RawBSONDocument) 
mydb = myclient['smackcoders'] 
mycol = mydb['logs'] 
from_date = "2019-10-09T10:32:08.438663" 
to_date = "2019-10-12T10:32:08.438671" 
for doc in mycol.find({"date": {'$gte': from_date, '$lte': to_date}}, {}, {'Page': [], '_id': 0}): 
    print(doc) 

显示错误:

Traceback (most recent call last): 
  File "temp3.py", line 20, in <module> 
    for doc in mycol.find({"date": {'$gte': from_date, '$lte': to_date}}, {}, {'url': [], '_id': 0}): 
  File "/home/paulsteven/.local/lib/python3.7/site-packages/pymongo/collection.py", line 1460, in find 
    return Cursor(self, *args, **kwargs) 
  File "/home/paulsteven/.local/lib/python3.7/site-packages/pymongo/cursor.py", line 145, in __init__ 
    raise TypeError("skip must be an instance of int") 
TypeError: skip must be an instance of int 

需要的输出:

["http://192.168.1.34/third.html","http://192.168.1.14/fourth.html",.....and goes on for a specified date] 

我不知道如何让它工作。查询在 mongodb 中有效,但在 python 中,它失败了。帮我解决一些问题。

请您参考如下方法:

您的 find 中有 3 个参数功能;你可能只需要 2;查询和投影。第三个参数是 skip,这就是它因该错误而失败的原因。

Mongo shell 只接受 2 个参数,因此它很可能会忽略第三个参数,这就是它看起来正常工作的原因。