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: {}}])
相关推荐
Rick199318 小时前
联合索引是按顺序排好序的
数据库·mysql
步十人18 小时前
【Redis】网络高并发模型
网络·数据库·redis
我是一颗柠檬18 小时前
【Redis】列表与集合Day4(2026年)
数据库·redis·后端·缓存
AOwhisky18 小时前
Ceph系列第三期:Ceph 集群核心配置与管理
linux·运维·数据库·笔记·ceph
陈天伟教授18 小时前
安装 AutoCAD 时,“可选工具“ 的详细说明。
数据库
zcn12618 小时前
举一反三思路思考形如(列=参数 or decode函数)
数据库·sql优化改写
Xzh042318 小时前
Redis黑马点评 实战复盘与面试高频考点详解
java·数据库·redis·面试
林的快手18 小时前
MySQL
数据库·oracle
身如柳絮随风扬19 小时前
MySQL 存储引擎深度解析:InnoDB vs MyISAM vs Memory,行锁实现与索引奥秘
数据库·mysql
KaMeidebaby19 小时前
卡梅德生物技术快报|基因测序技术在 46,XY 性发育障碍变异筛查中的流程与数据分析
服务器·前端·数据库·人工智能·算法·数据挖掘·数据分析