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: {}}])
相关推荐
韩zj5 分钟前
服务器定时备份数据库脚本
服务器·数据库·adb
笨蛋少年派16 分钟前
Maxwell数据变更捕获工具简介
数据库·mysql
谷新龙00123 分钟前
pg_clickhouse插件,在postgresql中借助clickhouse借用OLAP能力
数据库·clickhouse·postgresql
Hello.Reader25 分钟前
Flink SQL 的 SET 语句会话参数配置与快速自检(SQL CLI 实战)
数据库·sql·flink
老华带你飞32 分钟前
工会管理|基于springboot 工会管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring
自在极意功。32 分钟前
MyBatis配置文件详解:environments、transactionManager与dataSource全面解析
java·数据库·tomcat·mybatis
紫金桥软件33 分钟前
紫金桥软件 | 赋能工业数字化转型
数据库·国产化
Navicat中国36 分钟前
Navicat x 达梦技术指引 | 模型转换
数据库·达梦·navicat·概念模型·物理模型·逻辑模型·模型转换
邂逅星河浪漫37 分钟前
【MySQL 事务】详细介绍+实例
数据库·mysql·事务
tianyuanwo40 分钟前
RPM数据库锁竞争:原理、诊断与根治方案
数据库·rpm·bdb·命令挂起