mongodb的删除语句
转自: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" },