MongoDB查询各种参数
本文详细介绍了在Linux系统上手动配置Kubernetes集群的分步流程。主要内容包括:所有节点的基本配置(禁用Swap、设置主机名、内核调优、安装containerd);控制平面节点的kubeadm初始化;工作节点的加入方法;网络插件(Flannel/Calico)的安装;以及集群验证和必要附加组件(Metrics Server、Dashboard等)的部署。文章还提供了生产环境注意事项(高可
·
要查询MongoDB集合中的数据条数(文档数量),有两种常用方法,适用于不同场景:
1. countDocuments() - 精确计数(推荐)
// 查询整个集合的总文档数
db.collection.countDocuments({})
// 按条件计数(如:status为"active"的文档)
db.collection.countDocuments({ status: "active" })
特点:
✅ 精确统计文档数量(执行实际查询)
✅ 支持过滤条件
⚠️ 大型集合可能较慢(需遍历数据或索引)
2. estimatedDocumentCount() - 快速估算
// 快速返回集合的近似文档数
db.collection.estimatedDocumentCount()
特点:
⚡️ 极快(读取集合元数据,不扫描数据)
❌ 不支持查询条件
⚠️ 集群分片环境下结果可能略微滞后
⚠️ 不推荐的方法
// 已弃用(可能返回不准确结果)
db.collection.count() // 4.0+ 版本废弃
db.collection.find().count()
使用示例
假设集合名为 users:
// 精确统计所有用户
db.users.countDocuments({}) // 返回:15200
// 快速估算(约数)
db.users.estimatedDocumentCount() // 返回:~15000
// 统计状态为活跃的用户
db.users.countDocuments({ status: "active" }) // 返回:11200
选择建议:
| 方法 | 场景 |
|---|---|
countDocuments({}) |
需要精确总数,且集合规模中等 |
estimatedDocumentCount() |
大型集合快速获取近似值 |
countDocuments({条件}) |
需要按特定条件计数时 |
性能提示:对带条件的
countDocuments(),确保查询字段已建立索引,否则可能触发全表扫描!
在PyMongo中获取MongoDB集合的存储空间大小,可以使用database.command('collStats', collection_name)方法。以下是完整示例:
获取集合存储空间大小的代码
from pymongo import MongoClient
import pprint
# 连接MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database'] # 替换为实际数据库名
collection_name = 'your_collection' # 替换为实际集合名
# 获取集合统计信息
stats = db.command('collStats', collection_name)
# 打印关键存储信息
pprint.pprint({
'collection': collection_name,
'storageSize': stats['storageSize'], # 磁盘上分配的存储空间 (bytes)
'size': stats['size'], # 未压缩的数据总大小 (bytes)
'totalIndexSize': stats['totalIndexSize'], # 所有索引大小总和 (bytes)
'totalSize': stats['totalSize'] # 集合总占用空间 (storageSize + 索引大小)
})
# 换算为MB
print(f"\n详细空间使用 (MB):")
print(f"数据存储空间: {stats['storageSize'] / (1024 * 1024):.2f} MB")
print(f"原始数据大小: {stats['size'] / (1024 * 1024):.2f} MB")
print(f"索引占用空间: {stats['totalIndexSize'] / (1024 * 1024):.2f} MB")
print(f"总计空间占用: {stats['totalSize'] / (1024 * 1024):.2f} MB")
关键字段说明:
- storageSize:集合在磁盘上实际占用的存储空间(包含预分配空间)
- size:集合中所有文档的未压缩总大小(Bson格式)
- totalIndexSize:集合所有索引的总大小
- totalSize:集合总占用空间 = storageSize + totalIndexSize
其他有用空间信息:
# 查看每个索引的大小
print("\n索引详情:")
for index_name, size in stats['indexSizes'].items():
print(f"- {index_name}: {size / 1024:.2f} KB")
# 查看压缩信息(如果使用WiredTiger存储引擎)
if 'wiredTiger' in stats:
print(f"\n压缩比例: {stats['size'] / stats['storageSize']:.2f}:1")
实际输出示例:
{'collection': 'users',
'size': 25165824,
'storageSize': 8388608,
'totalIndexSize': 3686400,
'totalSize': 12075008}
详细空间使用 (MB):
数据存储空间: 8.00 MB
原始数据大小: 24.00 MB
索引占用空间: 3.52 MB
总计空间占用: 11.52 MB
重要注意事项:
storageSize≤size(因为存储引擎会压缩数据)- WiredTiger引擎默认使用Snappy压缩
totalSize是集合实际占用的总空间(包含碎片空间)- 对于分片集合,需要在每个分片上分别运行此命令
获取整个数据库的空间使用:
db_stats = db.command('dbStats')
print(f"\n数据库总空间: {db_stats['dataSize'] / (1024 * 1024):.2f} MB")
print(f"数据库存储大小: {db_stats['storageSize'] / (1024 * 1024):.2f} MB")
print(f"数据库索引总量: {db_stats['indexSize'] / (1024 * 1024):.2f} MB")
以下是通过 PyMongo 查看 MongoDB 常见参数和管理数据的实用指南:
1. 基础连接与管理
from pymongo import MongoClient
import pprint
# 创建连接 (带认证示例)
client = MongoClient(
host="localhost:27017",
username="admin",
password="yourpassword",
authSource="admin"
)
# 选择数据库和集合
db = client["your_database"]
collection = db["your_collection"]
2. 查看服务器基本参数
# 获取服务器版本信息
build_info = db.command("buildInfo")
print(f"MongoDB 版本: {build_info['version']}")
# 获取服务器状态
server_status = db.command("serverStatus")
print(f"运行时间: {server_status['uptime']}秒")
print(f"当前连接数: {server_status['connections']['current']}")
3. 数据库参数查看
# 查看数据库统计
db_stats = db.command("dbStats")
pprint.pprint({
"数据库名称": db_stats["db"],
"集合数量": db_stats["collections"],
"文档总数": db_stats["objects"],
"存储大小": f"{db_stats['storageSize']/(1024*1024):.2f} MB",
"索引大小": f"{db_stats['indexSize']/(1024*1024):.2f} MB"
})
# 查看所有集合空间占用
for coll_name in db.list_collection_names():
coll_stats = db.command("collStats", coll_name)
print(f"{coll_name}: {coll_stats['storageSize']/(1024*1024):.2f} MB")
4. 性能参数监控
# 获取当前操作
current_ops = db.current_op()
print("正在进行的操作:")
for op in current_ops["inprog"]:
print(f"- {op['command']} (已运行: {op['secs_running']}秒)")
# 查看索引使用统计
index_stats = []
for coll_name in db.list_collection_names():
stats = db[coll_name].aggregate([{"$indexStats": {}}])
index_stats.extend(list(stats))
print("\n索引使用情况:")
for idx in index_stats:
print(f"{idx['name']}: {idx['accesses']['ops']}次访问")
5. 配置参数查看
# 获取副本集配置 (若适用)
try:
repl_config = client.admin.command("replSetGetConfig")
members = repl_config["config"]["members"]
print(f"\n副本集成员: {[m['host'] for m in members]}")
except Exception as e:
print("不是副本集模式:", e)
# 查看当前配置参数
settings = client.admin.command("getCmdLineOpts")
print("\n启动参数:")
pprint.pp(settings["parsed"])
6. 安全参数与用户管理
# 查看当前用户权限
users_info = db.command("usersInfo")
print("\n数据库用户:")
for user in users_info["users"]:
print(f"- {user['user']} (角色: {', '.join([r['role'] for r in user['roles']])})")
# 检查认证配置
auth_info = client.admin.command({"getParameter": 1, "authenticationMechanisms": 1})
print("启用的认证机制:", auth_info["authenticationMechanisms"])
7. 维护操作示例
# 创建索引
collection.create_index([("field_name", pymongo.ASCENDING)], background=True)
# 压缩集合回收空间
db.command("compact", "your_collection")
# 热修改配置 (示例)
client.admin.command({
"setParameter": 1,
"logLevel": 1, # 设置日志级别
"slowOpThresholdMs": 100 # 慢查询阈值
})
8. 常用参数说明表
| 参数 | 查看命令 | 说明 |
|---|---|---|
| 运行时间 | serverStatus()['uptime'] |
服务器持续运行时间 |
| 内存使用 | serverStatus()['mem'] |
虚拟/常驻内存大小 |
| 连接数 | serverStatus()['connections'] |
当前/可用连接数 |
| 操作计数 | serverStatus()['opcounters'] |
增删改查操作次数 |
| 缓存命中率 | collStats()['wiredTiger']['cache'] |
数据缓存性能 |
| 慢查询 | profiling_level |
慢查询阈值设置 |
| 写关注 | getCmdLineOpts()['parsed']['replication'] |
写安全设置 |
完整示例输出
# 获取并格式化关键参数
def get_mongo_summary(client):
summary = {}
# 服务器基础信息
build_info = client.admin.command("buildInfo")
server_status = client.admin.command("serverStatus")
summary.update({
"版本": build_info["version"],
"运行时间(天)": round(server_status["uptime"] / 86400, 1),
"连接数": f"{server_status['connections']['current']}/{server_status['connections']['available']}"
})
# 数据库信息
db_stats = client.db_name.command("dbStats")
summary.update({
"集合数量": db_stats["collections"],
"文档总数": db_stats["objects"],
"存储空间(GB)": round(db_stats["storageSize"] / (1024**3), 2)
})
return summary
print("MongoDB 状态摘要:")
pprint.pp(get_mongo_summary(client))
安全建议
- 限制在生产环境执行
serverStatus和currentOp等性能敏感命令 - 通过角色控制访问权限:
# 创建只读用户
db.command("createUser", "monitor_user",
pwd="safe_password",
roles=[{"role": "read", "db": "admin"}])
- 启用SSL加密:
client = MongoClient(
"mongodb://example.com:27017/",
ssl=True,
ssl_cert_reqs=ssl.CERT_REQUIRED,
ssl_ca_certs='/path/to/ca.pem'
)
以上代码提供了通过 PyMongo 进行 MongoDB 参数查看和管理的全面方案,实际使用时请根据您的环境调整数据库名称、认证参数和安全设置。
更多推荐

所有评论(0)