MongoDB delete document

an introduction
The MongoDB remove() function is used to remove data from a collection.
MongoDB data can be updated using the update() function. It is a good habit to execute the find() command before executing the remove() function to determine whether the execution conditions are correct.
two grammar
The basic syntax format of the remove() method is as follows:
db.collection.remove(
   <query>,
   <justOne>
)
If your MongoDB is version 2.6 or later, the syntax is as follows:
db.collection.remove(
   <query>,
   {
     justOne: <boolean>,
     writeConcern: <document>
   }
)
Parameter Description:
query : (optional) The criteria for the deleted document.
justOne : (optional) If set to true or 1, only one document will be deleted.
writeConcern : (optional) The level at which the exception is thrown.
Three examples
The following documents we perform two insert operations:
  1. >db.col.insert({title: 'MongoDB 教程',
  2. description: 'MongoDB 是一个 Nosql 数据库',
  3. by: '菜鸟教程',
  4. url: 'http://www.runoob.com',
  5. tags: ['mongodb', 'database', 'NoSQL'],
  6. likes: 100
  7. })
Use the find() function to query data:
> db.col.find()
{ "_id" : ObjectId("56066169ade2f21f36b03137"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "菜鸟教程", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("5606616dade2f21f36b03138"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "菜鸟教程", "url" : "http://www.runoob.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
 
接下来我们移除 title 为 'MongoDB 教程' 的文档:
  1. >db.col.remove({'title':'MongoDB 教程'})
  2. WriteResult({ "nRemoved" : 2 }) # 删除了两条数据
  3. >db.col.find()
  4. # 没有数据
如果你只想删除第一条找到的记录可以设置 justOne 为 1,如下所示:
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)
如果你想删除所有数据,可以使用以下方式(类似常规 SQL 的 truncate 命令):
  1. >db.col.remove({})
  2. >db.col.find()
 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327073570&siteId=291194637