pymongo使用记录

pymongo使用

1、常用语法
# 列出有哪些数据库
conn.list_database_names()
# 列出有哪些表
dbconn.list_collection_names()
2、报错处理

1、报错:

Error happened when parse/import PM files 'Cursor' object has no attribute 'count'

4.0 API *已弃用:*该count()方法已弃用并且在事务中不起作用。

修正:

# 获取匹配过滤器的文档总数,或集合中的文档总数。
count_documents

# 获取集合中文档的大致数量。请注意,不像count_documents,estimated_document_count不接受过滤器。
estimated_document_count

eg

import pymongo

url = "mongodb://" + "root" + ":" + "root123" + "@" + "1.1.1.1" + ":" + "20000" + "/"
mongo_client = pymongo.MongoClient(url, serverSelectionTimeoutMS=10000, connectTimeoutMS=10000)
conn = mongo_client["database1"]
table_conn = conn["table1"]
# 过滤查询
table_conn.count_documents({"mec" : "GC_24-042_EA011_345482", "ntp" : "msrbs"})
# 查询总数
table_conn.estimated_document_count()

2、报错:

Database objects do not implement truth value testing or bool(). Please compare with None instead: database is not None
mongo_client = MongoClient(...)
# get a database object
db_obj = mongo_client['mydb']
if db_obj:
    # get a collection
    collection_obj = db_obj['my_collection']
    if collection_obj:
        # do a query
        # ...

改正

mongo_client = MongoClient(...)
# get a database object
db_obj = mongo_client['mydb']
if db_obj is not None:      <-- here
    # get a collection
    collection_obj = db_obj['my_collection']
    if collection_obj is not None:      <-- here
        # do a query
        # ...

3、报错

'Collection' object is not callable. If you meant to call the 'ensure_index' method on a 'Collection' object it is failing because no such method exists.

在 3.0 及以上版本ensure_index 已被删除。您现在应该create_index改用

def persist(self, document):
    collection.ensure_index([("nedn", 1)], unique=True)
    collection.insert_one(document)

可以改成

def persist(self, document):
    if not self.created_index:
        collection.create_index([("nedn", 1)], unique=True)
        self.created_index = True
    collection.insert_one(document)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值