码迷,mamicode.com
首页 > 数据库 > 详细

MongoDB CRUD之D

时间:2018-02-17 10:28:53      阅读:266      评论:0      收藏:0      [点我收藏+]

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

文档删除

命令 操作
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

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

原文地址:https://www.cnblogs.com/oneTOinf/p/8451397.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!