MongoDB quick start notes of 6 MongoDB delete document operation

  • 2020-06-01 11:13:40
  • OfStack

MongoDB is a cross-platform, document-oriented database that provides high performance, high availability and ease of scaling. MongoDB is a concept that works on collections and documents.

The document is a set of key-value pairs. The document has a dynamic mode. Dynamic mode means that files in the same collection do not have to have the same set of document fields or structures, and the same fields can hold different types of data.

db. Collection name.remove({query}, justOne)

query: filter conditions, optional

justOne: it is optional to delete only the first data in the query, if the value is true or 1, only 1 data will be deleted, and the default is false.

Prepare data: change age for _id 1 and 2 to 28

> db.student.update({_id:1},{$set:{age:28}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.update({_id:2},{$set:{age:28}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 28 }
{ "_id" : 2, "name" : "lisi", "age" : 28 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "skill" : [ "mongodb", "java" ] }

1. Use two parameters:

Delete the first data of age=28


> db.student.remove({age:28}, true)
WriteResult({ "nRemoved" : 1 })
> db.student.find()
{ "_id" : 2, "name" : "lisi", "age" : 28 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "skill" : [ "mongodb", "java" ] } 

2. Use one parameter:

Delete all data for age=28


> db.student.remove({age:28})
WriteResult({ "nRemoved" : 2 })
> db.student.find()
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "skill" : [ "mongodb", "java" ] } 

3. Delete all data of the collection, and the "{}" in parentheses must have, indicating the empty filter condition:


> db.student.remove({})
WriteResult({ "nRemoved" : 4 }) 

In addition, when using the remove() method to delete, only the data is deleted, and the table will still exist. Using the drop() method removes the table as well, and drop() is much more efficient than remove().


Related articles: