mongoDB數組操作器
$push會向數組末尾加入一個元素,如果數組不存在,則會創建這個數組。
增加評論comments:
db.blog.posts.update({"title":"a blog post"}
,{
$push:
{"comments":{"name":"joe","email":"joe@example.com"}}
}
)
最終的結果是:
{
"_id":ObjectId("8df8df78d7f7d8df7"),
"title":"a blog post"
"comments":[{
"name":"joe",
"email":"joe@example.com"
}]
}
$ne如果一個值不在數組里面,就加進去:
db.papers.update({"authors cited":{"$ne":"richie"}},
{$push:{"authors cited":"richie"}})
也可以用$addToSet完成同樣的功能:
db.papers.update({"_id":ObjectId("sdf9sd7f67df89d")},
{"$addToSet":{"authors cited":"richie"}})
$addToSet和$each組合起來,可以添加多個不同的值:
db.papers.update({"_id":ObjectId("sdf9sd7f67df89d")},
{"$addToSet":{"authors cited":{"$each":["richie","dff","dsf"]}}})
$pop刪除數組中的元素:
刪除末尾的元素:{$pop:{key:1}}
刪除頭部的元素:{$pop:{key:-1}}
$pull基於特定條件刪除元素:
db.lists.insert({"todo":["dishes","laundry","dry cleaning"]})
db.lists.update({},{"$pull":{"todo":"laundry"}})
修改數組元素的數量:
{
"_id":ObjectId("df89d8fd7d"),
"content":"...",
"comments":[
{
"comment":"good post",
"author":"joy",
"votes":0
},
{
"comment":"good post",
"author":"joyn",
"votes":0
},
{
"comment":"good post",
"author":"andy",
"votes":0
}
]
}
如果想增加第一個評論的投票數量:
db.blog.update("post":post_id},{"$inc":{"comments.0.votes"}:1})
修改用戶名:($用於定位已匹配的的元素,如果多個,就匹配第一個)
db.blog.update({comments.author:"andy"}:{"$set":{"comments.$.author":"jim"}})