MongoDB 的日常使用常常从几个小需求开始:模糊查询、按条件删除、批量替换字段、检查索引和判断事务支持。真正需要注意的是,MongoDB 更新数据很灵活,也更需要 dry-run 和条件约束。
先区分查询和修正
公开笔记里可以记录通用模式,但不要保留真实业务集合名、内网工单、真实 ID 或生产条件。处理线上数据时至少分三步:
- 先
find查出候选数据。 - 再统计数量和抽样。
- 最后才执行
update、delete或save。
能 dry-run 的地方一定先 dry-run,不能 dry-run 时也要先把查询条件缩到足够明确。
使用 regex 查找异常字段
比如要查找某个时间字段中是否混入了中文冒号,可以用 $regex:
db.collection.find({
business_start_time: { $regex: ":" }
});
多个字段同时检查时可以配合 $or:
db.collection.find({
$or: [
{ business_am_start_time: { $regex: ":" } },
{ business_am_end_time: { $regex: ":" } },
{ business_pm_start_time: { $regex: ":" } },
{ business_pm_end_time: { $regex: ":" } }
]
});
这种查询适合做数据质量扫描,但如果集合很大,要留意正则查询是否能使用索引。
逻辑操作符怎么组合
MongoDB 常用逻辑操作符:
$and:多个条件同时满足。$or:多个条件满足任意一个。$not:条件取反。$nor:多个条件都不满足。
示例:
db.collection.find({
$and: [
{ status: "enabled" },
{ quota: { $lte: 0 } },
{ date: "2026-07-05" }
]
});
很多时候 $and 可以省略,因为对象中的多个字段默认就是与关系。但显式写出来适合复杂脚本和审计记录。
批量替换字段要先做保护
如果要把字段中的中文冒号替换成英文冒号,可以写成脚本,但要注意空值判断:
db.collection.find({
business_start_time: { $regex: ":" }
}).forEach(function(item) {
if (item.business_start_time != null) {
item.business_start_time = String(item.business_start_time).replace(":", ":");
db.collection.save(item);
}
});
更稳的做法是先只打印待修正数据:
db.collection.find({
business_start_time: { $regex: ":" }
}).forEach(function(item) {
printjson({
id: item._id,
before: item.business_start_time,
after: String(item.business_start_time).replace(":", ":")
});
});
确认数量和样本无误后再执行写入。
删除数据必须有精确条件
删除操作不要只靠单个模糊条件,至少组合业务 ID、状态、日期、数量等约束:
db.collection.deleteMany({
$and: [
{ business_id: "example" },
{ quota: { $lte: 0 } },
{ date: "2026-07-05" }
]
});
执行前先用同样条件跑:
db.collection.countDocuments({
business_id: "example",
quota: { $lte: 0 },
date: "2026-07-05"
});
实用结论
MongoDB 的优势是灵活,但灵活也意味着容易误操作。日常查询可以掌握 $regex、$or、$and 和字段替换脚本;涉及修正和删除时,先查、再数、再抽样、最后写入,并保留条件和结果记录。
正文完




