文档删除
命令 | 操作 |
---|---|
db.collection.deleteOne() |
即使多个文档可能匹配指定的过滤器,也要删除与指定筛选器匹配的单个文档。 |
db.collection.deleteMany() |
删除匹配指定过滤器的所有文档。 |
db.collection.remove() |
删除单个文档或匹配指定筛选器的所有文档 |
其他的可以参考这里
deleteOne
格式
db.collection.deleteOne(
<filter>,
{
writeConcern: <document>,
collation: <document>
}
)
删除与筛选器匹配的第一个文档。用于 capped collection 时会抛出一个WriteError异常。
> db.orders.find().pretty()
{
"_id" : ObjectId("563237a41a4d68582c2509da"),
"stock" : "Brent Crude Futures",
"qty" : 250,
"type" : "buy-limit",
"limit" : 48.9,
"creationts" : ISODate("2015-11-01T12:30:15Z"),
"expiryts" : ISODate("2015-11-01T12:35:15Z"),
"client" : "Crude Traders Inc."
}
> try {
... db.orders.deleteOne( { "_id" : ObjectId("563237a41a4d68582c2509da") } );
... } catch (e) {
... print(e);
... }
{ "acknowledged" : true, "deletedCount" : 1 }
> db.orders.find().pretty()
>
删除日期比较早的
> db.orders.find().pretty()
{
"_id" : ObjectId("563237a41a4d68582c2509da"),
"stock" : "Brent Crude Futures",
"qty" : 250,
"type" : "buy-limit",
"limit" : 48.9,
"creationts" : ISODate("2015-11-01T12:30:15Z"),
"expiryts" : ISODate("2015-11-01T12:35:15Z"),
"client" : "Crude Traders Inc."
}
> try {
... db.orders.deleteOne( { "expiryts" : { $lt: ISODate("2015-11-01T12:40:15Z") } } );
... } catch (e) {
... print(e);
... }
{ "acknowledged" : true, "deletedCount" : 1 }
> db.orders.find().pretty()
>
deleteMany
格式
db.collection.deleteMany(
<filter>,
{
writeConcern: <document>,
collation: <document>
}
)
用于 capped collection 时会抛出一个WriteError异常。
> db.orders.find().pretty()
{
"_id" : ObjectId("563237a41a4d68582c2509da"),
"stock" : "Brent Crude Futures",
"qty" : 250,
"type" : "buy-limit",
"limit" : 48.9,
"creationts" : ISODate("2015-11-01T12:30:15Z"),
"expiryts" : ISODate("2015-11-01T12:35:15Z"),
"client" : "Crude Traders Inc."
}
> try {
... db.orders.deleteMany( { "client" : "Crude Traders Inc." } );
... } catch (e) {
... print (e);
... }
{ "acknowledged" : true, "deletedCount" : 1 }
> db.orders.find().pretty()
>
其实跟deleteOne差不多
remove
格式
db.collection.remove(
<query>,
<justOne>
)
从集合中删除所有文档
> db.bios.find().count()
10
> db.bios.remove( { } )
WriteResult({ "nRemoved" : 10 })
> db.bios.find().count()
0
删除匹配条件的所有文档
> db.products.remove( { qty: { $gt: 20 } } )
> db.products.find( { qty: { $gt: 20 } } ).count()
0
使用参数justOne删除一条
> db.products.remove( { qty: { $gt: 20 } }, true )
> db.products.find( { qty: { $gt: 20 } } ).count()
10