MongoDB 删除文档 笔记

删除文档

1. db.collection.remove()

  • 默认情况下,remove 命令会删除所有符合筛选条件的文档
  • 如果只想删除满足条件的第一篇文档,可以使用 justOne 选项
// 如果只想删除满足条件的第一篇文档,可以使用 justOne 选项 示例
> db.accounts.find({}, {"name": 1, balance: 1})
{ "_id" : ObjectId("6327179289c04594a4b8f675"), "name" : "bob", "balance" : 100 }
{ "_id" : ObjectId("632717a889c04594a4b8f676"), "name" : "alice", "balance" : 90 }
{ "_id" : ObjectId("632873b543489401f4ff49c2"), "name" : "karen", "balance" : 250 }
{ "_id" : ObjectId("63287530f8526f895273d037"), "name" : "jack" }
{ "_id" : ObjectId("6329d648f5bd549a110fc5d0"), "name" : "blice" }
{ "_id" : ObjectId("6329d655f5bd549a110fc5d1"), "name" : "clice", "balance" : 90 }
{ "_id" : ObjectId("634440158bad614c1c907498"), "name" : "bili" }
>
>
> db.accounts.remove({"balance": {$lt: 100}}, {justOne: true})
WriteResult({ "nRemoved" : 1 })

> db.accounts.find({}, {"name": 1, balance: 1})
{ "_id" : ObjectId("6327179289c04594a4b8f675"), "name" : "bob", "balance" : 100 }
{ "_id" : ObjectId("632873b543489401f4ff49c2"), "name" : "karen", "balance" : 250 }
{ "_id" : ObjectId("63287530f8526f895273d037"), "name" : "jack" }
{ "_id" : ObjectId("6329d648f5bd549a110fc5d0"), "name" : "blice" }
{ "_id" : ObjectId("6329d655f5bd549a110fc5d1"), "name" : "clice", "balance" : 90 }
{ "_id" : ObjectId("634440158bad614c1c907498"), "name" : "bili" }
>

// 删除所有文档
> db.accounts.remove({})
WriteResult({ "nRemoved" : 6 })
> db.accounts.find({}, {"name": 1, balance: 1})
>

2. 删除集合 db.collection.drop()

命令: db.<collection>.drop({writeConcern: <document>})

  • writeConcern 文档定义了本次集合删除操作的安全写级别
  • drop 命令可以删除整个集合,包括集合中的文档和集合的索引
  • 如果集合中的文档数量很大,使用remove删除所有文档的效率不高,这种情况下,可以使用drop命令删除集合,然后创建空集合,并建立索引
> show collections;
accounts
delete_me
my_test
products
>
> db.accounts.drop()
true

> show collections;
delete_me
my_test
products
>
posted @ 2022-10-12 00:57  郭赫伟  阅读(32)  评论(0编辑  收藏  举报