当前位置:Gxlcms > 数据库问题 > MongoDB CRUD之D

MongoDB CRUD之D

时间:2021-07-01 10:21:17 帮助过:3人阅读

<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

标签:异常   iso   bio   多个   gpo   span   文档   oda   命令   

人气教程排行