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: {}}])
相关推荐
Zfox_1 小时前
Redis:Hash数据类型
服务器·数据库·redis·缓存·微服务·哈希算法
陈丹阳(滁州学院)3 小时前
若依添加添加监听容器配置(删除键,键过期)
数据库·oracle
远方16094 小时前
14-Oracle 23ai Vector Search 向量索引和混合索引-实操
数据库·ai·oracle
GUIQU.5 小时前
【Oracle】数据仓库
数据库·oracle
恰薯条的屑海鸥5 小时前
零基础在实践中学习网络安全-皮卡丘靶场(第十六期-SSRF模块)
数据库·学习·安全·web安全·渗透测试·网络安全学习
咖啡啡不加糖5 小时前
Redis大key产生、排查与优化实践
java·数据库·redis·后端·缓存
曼汐 .5 小时前
数据库管理与高可用-MySQL高可用
数据库·mysql
2301_793102496 小时前
Linux——MySql数据库
linux·数据库
喵叔哟6 小时前
第4章:Cypher查询语言基础
数据库
刘 大 望6 小时前
数据库-联合查询(内连接外连接),子查询,合并查询
java·数据库·sql·mysql