轉自:http://www.mongoing.com/docs/tutorial/remove-documents.html
刪除的方法
MongoDB provides the following methods to delete documents of a collection:
db.collection.remove() | Delete a single document or all documents that match a specified filter. |
db.collection.deleteOne() | Delete at most a single document that match a specified filter even though multiple documents may match the specified filter. 3.2 新版功能. |
db.collection.deleteMany() | 刪除所有匹配指定過濾條件的文檔. 3.2 新版功能. |
你可以指定條件或過濾器來找到要刪除的文檔.這些 filters 使用與讀操作相同的語法:
-
query filter document 能夠用 <field>:<value> 表達式指定相等條件並以此選出所有包含指定 <value> 的 <field> 的文檔:
{ <field1>: <value1>, ... }
-
A query filter document can use the query operators to specify conditions in the following form:
{ <field1>: { <operator1>: <value1> }, ... }
刪除的行為表現
索引
Delete operations do not drop indexes, even if deleting all documents from a collection.
原子性
MongoDB中所有的寫操作在單一文檔層級上是原子的.更多關於MongoDB和原子性的信息,請參見 原子性和事務處理.
示例集合
本頁提供了在 mongo shell中刪除操作的例子.在:program:mongo shell中運行如下命令以向例子中涉及到的 users 集合填入數據:
注解
如果 users 集合中已經包含了相同 _id 值的文檔,你需要在插入示例文檔前 drop 該集合( db.users.drop() ).
db.users.insertMany( [ { _id: 1, name: "sue", age: 19, type: 1, status: "P", favorites: { artist: "Picasso", food: "pizza" }, finished: [ 17, 3 ], badges: [ "blue", "black" ], points: [ { points: 85, bonus: 20 }, { points: 85, bonus: 10 } ] }, { _id: 2, name: "bob", age: 42, type: 1, status: "A", favorites: { artist: "Miro", food: "meringue" }, finished: [ 11, 25 ], badges: [ "green" ], points: [ { points: 85, bonus: 20 }, { points: 64, bonus: 12 } ] }, { _id: 3, name: "ahn", age: 22, type: 2, status: "A", favorites: { artist: "Cassatt", food: "cake" }, finished: [ 6 ], badges: [ "blue", "red" ], points: [ { points: 81, bonus: 8 }, { points: 55, bonus: 20 } ] }, { _id: 4, name: "xi", age: 34, type: 2, status: "D", favorites: { artist: "Chagall", food: "chocolate" }, finished: [