MongoDB
更新
区别更新与查询操作符的语法
基本上,更新操作符是前缀,查询操作符通常是中缀
collection.update({ price: {$lte: 10 }}, { $addToSet : { tags: ‘cheap’ }})
多文档更新
默认更新操作只更新匹配到的第一个文档,否则添加 {multi: true}
upsert
不存在时则插入,存在时更新 添加{upsert: true}
Get WhySoSilent?’s stories in your inbox
Join Medium for free to get updates from this writer.
$inc
更新、原子操作、删除
updata({},{‘$set’ : {email: ‘new address’}})
updata({},{‘$push’: {‘arrayName’: {…}}})
索引
为文档建立一个唯一性索性可用于做短名称主键
db.collection.ensure({slug,1},{unique:true})
有唯一性索引的插入操作使用安全模式方能确认插入是否成功,因为可能造成不唯一插入冲突
查询选择器
< <= > >=
$lt $lte $gt $gte
范围选择器涉及到了类型!注意类型不同时的差异
集合操作符
{‘product.color’ : { $nin : [‘black’,’blue’] }
$in 类似于或运算
$nin 与给定元素都不匹配时才返回该文档
$all 与给定的每个元素都匹配时返回文档,如在数组匹配当中
牢记 $in 和 $all 都能利用索引,但 $nin 不能 !
布尔操作符
$ne 不等于
$ne 无法利用索引,实践中最好和其他操作符结合使用否则查询效率可能不高






