Mongodb更新數組$pull修飾符 (mongodb 修改器($inc/$set/$unset/$push/$pop/upsert))


 

 

mongodb 修改器($inc/$set/$unset/$push/$pop/upsert))   https://www.jb51.net/article/112588.htm
http://blog.csdn.net/yaomingyang/article/details/78701643

一、$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
來源:CSDN
原文:https://blog.csdn.net/yaomingyang/article/details/78701643
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM