You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyMongo执行MongoDB查询时出现OperationFailure错误:Skip值必须非负,但接收到-1 求助

解决PyMongo中Skip值为负数的OperationFailure错误

嘿,这个问题很好解决,咱们先从报错信息入手——OperationFailure: Skip value must be non-negative, but received: -1,这说明你计算的doc_count -1得到了负数,也就是你的doc_count值是0,集合里根本没有文档,自然没法跳过-1条啦。

看你的代码,应该是想获取集合里的最后一条文档对吧?那咱们分两步来修复:

第一步:先处理集合为空的情况

先确保集合里有文档再执行skip操作,避免出现负数:

import json
from bson import json_util

doc_count = collection.count_documents({})
if doc_count > 0:
    last_doc = collection.find_one({}, skip=doc_count - 1)
    oid = json.dumps(last_doc['_id'], default=json_util.default)
else:
    print("集合中没有任何文档,无法获取最后一条数据")

第二步:用更高效的方式获取最后一条文档

其实用skip来取最后一条文档的效率很低,尤其是当集合里文档很多的时候,MongoDB需要跳过前面所有文档才能拿到最后一条。更优的做法是通过倒序排序直接取第一条:

import json
from bson import json_util

# 按_id倒序排序(_id默认包含时间戳,倒序就是最新插入的文档)
last_doc = collection.find_one({}, sort=[('_id', -1)])
if last_doc:
    oid = json.dumps(last_doc['_id'], default=json_util.default)
else:
    print("集合中没有任何文档")

这种方式不仅避免了skip的性能问题,还能自然处理集合为空的情况(此时last_doc会是None),一举两得~

内容的提问来源于stack exchange,提问作者Vijay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:52:44