MongoDB 常用查询语句/技巧
· 阅读需 2 分钟
转换为 UTC 时间字符串
// 转换为 UTC 时间字符串
db.collection.find({
timestamp: { $gte: new Date( new Date("2025-03-22T00:00:00+08:00").toISOString()) }
});
创建视图
// ============== AI800 A相进线温度 ==========
db.AI800.drop();
db.createView(
"AI800", // 视图名称
"equipment-1123", // 源集合
[
{ $match: { "code": "AI424" } }, // 过滤条件
]
)
db.AI800.find();
MongoDB 储存空间优化
数据库状态查询
db.stats(1024*1024); // 输出单位为 MB
查询结果说明:
{
"db": "tmp_dev",
"collections": Long("275"),
"views": Long("0"),
"objects": Long("7891781"), // 文档总数
"avgObjSize": 234.529085766572, // 单个文档的平均大小,单位是:byte
"dataSize": 1765.11019039154, // 逻辑大小,不压缩的情况下,数据大小
"storageSize": 299.5, // 物理大小
"indexes": Long("281"), // 索引数量
"indexSize": 123.61328125, // 索引占用的存储空间
"totalSize": 423.11328125, // 总存储空间 = storageSize + indexSize
"scaleFactor": Long("1048576"), // 缩放因子, 1048576 = 1024 * 1024, 即 MB
"fsUsedSize": 126627.28515625, // 文件系统已使用的存储空间
"fsTotalSize": 181303.5546875, // 文件系统总存储空间
"ok": 1
}
空间优化
1. 删除 collection 是可以直接释放空间的
2. 删除 collection 里面的数据是不会直接释放空间,需要执行 db.runCommand({compact:"collectuinName"})
优化脚本
for (var collectionName of db.getCollectionNames()) {
// 清空数据
if (collectionName.startsWith("equipment")
|| collectionName.startsWith("transformer")
|| collectionName.startsWith("circuit-breaker")) {
// db.getCollection(collectionName).deleteMany({});
// db.runCommand({
// compact: collectionName
// })
db.getCollection(collectionName).drop();
}
}
字段排序
.sort()
, 1
增序, -1
降序。
db.getCollection("transformer-1000").find({
"code": "AI801"
}).sort({
"dataTime": -1
}).limit(1000);