发布于 2015-09-14 14:52:19 | 140 次阅读 | 评论: 0 | 来源: 网络整理
Of the four basic database operations (i.e. CRUD), delete operations are those that remove documents from a collection in MongoDB.
For general information about write operations and the factors that affect their performance, see 写; for documentation of other CRUD operations, see the 核心操作(CRUD) page.
The remove() method in the mongo shell provides this operation, as do corresponding methods in the drivers.
注解
As of these driver versions, all write operations will issue a getLastError command to confirm the result of the write operation:
{ getLastError: 1 }
Refer to the documentation on write concern in the 写 document for more information.
Use the remove() method to delete documents from a collection. The remove() method has the following syntax:
db.collection.remove( <query>, <justOne> )
Corresponding operation in SQL
The remove() method is analogous to the DELETE statement, and:
remove() deletes documents from the collection. If you do not specify a query, remove() removes all documents from a collection, but does not remove the indexes. [1]
注解
For large deletion operations, it may be more efficient to copy the documents that you want to keep to a new collection and then use drop() on the original collection.
If there is a <query> argument, the remove() method deletes from the collection all documents that match the argument.
The following operation deletes all documents from the bios collection where the subdocument name contains a field first whose value starts with G:
db.bios.remove( { 'name.first' : /^G/ } )
If there is a <query> argument and you specify the <justOne> argument as true or 1, remove() only deletes a single document from the collection that matches the query.
The following operation deletes a single document from the bios collection where the turing field equals true:
db.bios.remove( { turing: true }, 1 )
If there is no <query> argument, the remove() method deletes all documents from a collection. The following operation deletes all documents from the bios collection:
db.bios.remove()
注解
This operation is not equivalent to the drop() method.
[1] | To remove all documents from a collection, it may be more efficient to use the drop() method to drop the entire collection, including the indexes, and then recreate the collection and rebuild the indexes. |
You cannot use the remove() method with a capped collection.
If the <query> argument to the remove() method matches multiple documents in the collection, the delete operation may interleave with other write operations to that collection. For an unsharded collection, you have the option to override this behavior with the $isolated isolation operator, effectively isolating the delete operation from other write operations. To isolate the operation, include $isolated: 1 in the <query> parameter as in the following example:
db.bios.remove( { turing: true, $isolated: 1 } )