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)