MongoDB CRUD之D
阿新 • • 發佈:2018-02-17
doc capped ios span 日期比較 limit ... 日期 ack
文檔刪除
命令 | 操作 |
---|---|
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
MongoDB CRUD之D