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: {}}])
相关推荐
姚远Oracle ACE1 小时前
解读Oracle AWR报告:Global Cache and Enqueue Services - Workload Characteristics
数据库·oracle
流星白龙1 小时前
【Qt】7.信号和槽_connect函数用法(2)
java·数据库·qt
麦麦麦造3 小时前
小小 Postgres,何以替代 Redis、MongoDB 甚至 ES?
redis·mongodb·elasticsearch·postgresql
Zzz 小生3 小时前
Claude Code学习笔记(四)-助你快速搭建首个Python项目
大数据·数据库·elasticsearch
nongcunqq6 小时前
abap 操作 excel
java·数据库·excel
rain bye bye7 小时前
calibre LVS 跑不起来 就将setup 的LVS Option connect下的 connect all nets by name 打开。
服务器·数据库·lvs
阿里云大数据AI技术8 小时前
云栖实录|MaxCompute全新升级:AI时代的原生数据仓库
大数据·数据库·云原生
不剪发的Tony老师9 小时前
Valentina Studio:一款跨平台的数据库管理工具
数据库·sql
weixin_307779139 小时前
在 Microsoft Azure 上部署 ClickHouse 数据仓库:托管服务与自行部署的全面指南
开发语言·数据库·数据仓库·云计算·azure
六元七角八分9 小时前
pom.xml
xml·数据库