当前位置:   article > 正文

Mongodb使用指定索引删除数据_mongodb deletemany

mongodb deletemany

回顾Mongodb删除语法

  1. db.collection.deleteMany(
  2. <filter>,
  3. {
  4. writeConcern: <document>,
  5. collation: <document>,
  6. hint: <document|string>
  7. }
  8. )

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

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

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

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

为字段member和status添加索引

  1. db.members.createIndex({"member": 1})
  2. db.members.createIndex({"status": 1})

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

db.members.aggregate([{$indexStats: {}}])

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

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

  1. db.members.deleteMany(
  2. { "points": { $lte: 20 }, "status": "P" },
  3. { hint: { status: 1 } }
  4. )
  5. {
  6. "acknowledged" : true,
  7. "deletedCount" : 3
  8. }

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

db.members.aggregate([{$indexStats: {}}])

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/878390
推荐阅读
相关标签
  

闽ICP备14008679号