mongodb 修改器($inc/$set/$unset/$push/$pop/upsert)) https://www.jb51.net/article/112588.htm

一、$pull修饰符会删除掉数组中符合条件的元素,使用的格式是:

{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }


二、指定一个值删除所有的列表

给一个stores集合下的文档

{

_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" ]

}


如下操作更新所有的文档在集合stores中的​​"apples"和"oranges"在数组fruits中和删除数组vegetables中的"carrots"​

db.stores.update( { }, { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } }, { multi: true } )

操作后的结果是:


{

"_id" : 1,

"fruits" : [ "pears", "grapes", "bananas" ],

"vegetables" : [ "celery", "squash" ]

}

{

"_id" : 2,

"fruits" : [ "plums", "kiwis", "bananas" ],

"vegetables" : [ "broccoli", "zucchini", "onions" ]

}



三、$pull删除所有符合条件的元素

根据集合profiles集合文档

{ _id: 1, votes: [ 3, 5, 6, 7, 7, 8 ] }

如下操作会删除掉votes数组中元素大于等于6的元素

db.profiles.update( { _id: 1 }, { $pull: { votes: { $gte: 6 } } } )

操作 之后数组中都是小于6的元素

{ _id: 1, votes: [ 3, 5 ] }

四、从一个数组嵌套文档中删除元素

一个survey集合包含如下文档

{

_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 }

]

}

五、如下集合文档是数组套数组类型

{

_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 } ] }

]

}



作者:随风yy

版权声明:本文为博主原创文章,请附上博文链接!