1、$pull修飾符會刪除掉數組中符合條件的元素,使用的格式是:mongodb
{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }數組
2、指定一個值刪除全部的列表
給一個stores集合下的文檔app
{
_id: 1,
fruits: [ "apples", "pears", "oranges", "grapes", "bananas" ],
vegetables: [ "carrots", "celery", "squash", "carrots" ]
}
{
_id: 2,
fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ],
vegetables: [ "broccoli", "zucchini", "carrots", "onions" ]
}
post
"apples"和"oranges"在數組fruits
中和刪除數組vegetables
中的"carrots"
操做後的結果是:
{
"_id" : 1,
"fruits" : [ "pears", "grapes", "bananas" ],
"vegetables" : [ "celery", "squash" ]
}
{
"_id" : 2,
"fruits" : [ "plums", "kiwis", "bananas" ],
"vegetables" : [ "broccoli", "zucchini", "onions" ]
}
ui
3、$pull刪除全部符合條件的元素
根據集合profiles集合文檔spa
{ _id: 1, votes: [ 3, 5, 6, 7, 7, 8 ] }.net
以下操做會刪除掉votes數組中元素大於等於6的元素
db.profiles.update( { _id: 1 }, { $pull: { votes: { $gte: 6 } } } )code
操做 以後數組中都是小於6的元素
{ _id: 1, votes: [ 3, 5 ] }htm
4、從一個數組嵌套文檔中刪除元素
一個survey集合包含以下文檔blog
{
_id: 1,
results: [
{ item: "A", score: 5 },
{ item: "B", score: 8, comment: "Strongly agree" }
]
}
{
_id: 2,
results: [
{ item: "C", score: 8, comment: "Strongly agree" },
{ item: "B", score: 4 }
]
}
以下操做將會刪除掉數組results中元素item等於B、元素score等於8的文檔集合
db.survey.update(
{ },
{ $pull: { results: { score: 8 , item: "B" } } },
{ multi: true }
)
操做後的結果是:
{
"_id" : 1,
"results" : [ { "item" : "A", "score" : 5 } ]
}
{
"_id" : 2,
"results" : [
{ "item" : "C", "score" : 8, "comment" : "Strongly agree" },
{ "item" : "B", "score" : 4 }
]
}
5、以下集合文檔是數組套數組類型
{
_id: 1,
results: [
{ item: "A", score: 5, answers: [ { q: 1, a: 4 }, { q: 2, a: 6 } ] },
{ item: "B", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 9 } ] }
]
}
{
_id: 2,
results: [
{ item: "C", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 7 } ] },
{ item: "B", score: 4, answers: [ { q: 1, a: 0 }, { q: 2, a: 8 } ] }
]
}
能夠使用$elemMatch匹配多個條件
db.survey.update(
{ },
{ $pull: { results: { answers: { $elemMatch: { q: 2, a: { $gte: 8 } } } } } },
{ multi: true }
)
操做後的結果是:{ "_id" : 1, "results" : [ { "item" : "A", "score" : 5, "answers" : [ { "q" : 1, "a" : 4 }, { "q" : 2, "a" : 6 } ] } ]}{ "_id" : 2, "results" : [ { "item" : "C", "score" : 8, "answers" : [ { "q" : 1, "a" : 8 }, { "q" : 2, "a" : 7 } ] } ]}