Mongodb使用指定索引删除数据

回顾Mongodb删除语法

复制代码
db.collection.deleteMany(
  <filter>,
  {
    writeConcern: <document>,
    collation: <document>,
    hint: <document|string>
  }
)

删除语法中,除了指定过滤器外,还可以指定写入策略,字符序和使用的索引。

本文通过翻译整理mongodb官方文档,实践使用指定的索引删除数据。

首先,创建测试集合members,集合中包含_id,member,status,points,misc1, misc2两个字段

复制代码
db.members.insertMany([
   { "_id" : 1, "member" : "abc123", "status" : "P", "points" :  0,  "misc1" : null, "misc2" : null },
   { "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60,  "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" },
   { "_id" : 3, "member" : "lmn123", "status" : "P", "points" :  0,  "misc1" : null, "misc2" : null },
   { "_id" : 4, "member" : "pqr123", "status" : "D", "points" : 20,  "misc1" : "Deactivated", "misc2" : null },
   { "_id" : 5, "member" : "ijk123", "status" : "P", "points" :  0,  "misc1" : null, "misc2" : null },
   { "_id" : 6, "member" : "cde123", "status" : "A", "points" : 86,  "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }
])

为字段member和status添加索引

复制代码
db.members.createIndex({"member": 1})
db.members.createIndex({"status": 1})

通过$indexStats查看索引使用情况

复制代码
db.members.aggregate([{$indexStats: {}}])

在"accesses.ops"字段中,能够看到新添加的索引访问数量都是0

执行带有指定索引的删除脚本,指定使用索引"status_1",删除成功

复制代码
db.members.deleteMany(
    { "points": { $lte: 20 }, "status": "P" },
    { hint: { status: 1 } }
)

{
	"acknowledged" : true,
	"deletedCount" : 3
}

重新查看索引使用情况,能够看到"status_1"索引访问次数为1

复制代码
db.members.aggregate([{$indexStats: {}}])
相关推荐
Hello.Reader1 小时前
Redis 延迟监控深度指南
数据库·redis·缓存
ybq195133454311 小时前
Redis-主从复制-分布式系统
java·数据库·redis
好奇的菜鸟4 小时前
如何在IntelliJ IDEA中设置数据库连接全局共享
java·数据库·intellij-idea
tan180°4 小时前
MySQL表的操作(3)
linux·数据库·c++·vscode·后端·mysql
满昕欢喜5 小时前
SQL Server从入门到项目实践(超值版)读书笔记 20
数据库·sql·sqlserver
Hello.Reader6 小时前
Redis 延迟排查与优化全攻略
数据库·redis·缓存
简佐义的博客7 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang
爬山算法7 小时前
MySQL(116)如何监控负载均衡状态?
数据库·mysql·负载均衡
老纪的技术唠嗑局10 小时前
OceanBase PoC 经验总结(二)—— AP 业务
数据库
阿里云大数据AI技术10 小时前
OpenSearch 视频 RAG 实践
数据库·人工智能·llm