MongoDB 常用操作符
2020-02-09 本文已影响0人
Guang777
MongoDB 常用操作符
比较运算符
-
$eq: (equal)等于 -
$gt:(greater than)大约 -
$gte: (greater than equal)大约等于 -
$in:等于数组中的某一项,{field:{$in:{value1,value2...}}} -
$lt:(less than)小于 -
$lte:(less than equal)小于等于 -
$ne:(not equal)不等于 -
$nin:(not in)不等于数组中的任何一项
逻辑运算符
-
$and:并且,{$and:[{expression1},{expression2},{expression3}...],等价于{{expression1},{expression2},{expression3}} -
$or:或者,{$or:[{expression1},{expression2},{expression3}]} -
$nor:对$or的否定,{expression1},{expression2},{expression3}至少有一个不成立 -
$not:不等于,{$not:value}
元素运算符
-
$exits:-
{field:{$exits:true,}}:返回包含该字段的文档 -
{field:{$exits:false,}}:返回不包含该字段的文档
-
-
$type:{field:{$type:[{type1},{type2}]}:返回该字段的数据类型是type1或者type2的文档 -
$mod:{field:{$mod:[divisor,remainder]}}:返回该字段的数值和divisor的余数等于remainder的文档 -
$regex:表示使用正则运算符,可以使用以下任何一种形式:{field:{'$regex':/pattern/,'$options':'<options>'}}{field:{'$regex':'pattern','$options':'<options>'}}-
{field:{'$regex':/pattern/<options>}}
其中的options可以为: - i:忽略大小写
- m:允许跨行
- x:忽略pattern中的空格
- s:允许
.(dot)匹配所有字符
为了方便起见,也可以记为: {field:/pattern/<options>}{name:{$in:[/^acme/i,/^ack/]}}{name:{'$regex':/acme.*corp/,'$options':'si'}}
数组运算符
-
$all:{field:{$all:[value1,value2,...]}}返回指定字段包含全部value1,value2...的文档 -
$elemMatch:{field:{$elemMatch:[query1,query2...]}}:返回至少满足一个条件的文档 -
$size:{field:{$size:value}}:返回该字段数组包含的元素个数等于value的文档
更新操作符
-
$currentDate:-
{'$currentDate':{field1:typeSpecification1,field2:typerSpecification2,...}}:将field1和field2设置为当前日期 - 当typeSpecification为true时,会将field作为date类型设置成当前日期
- 当typeSpecification为
{'$type':'timestamp'}或{'$type':'date'}(默认类型)时,
会将field根据要求的类型设置为当前日期 {$currentDate:{lastMofified:true, 'cancellation.date':{$type:'timestamp'}}}
-
-
$inc:{$inc:{field1:value1,field2:value2,...}}:将特定字段累加某一数字 -
$min:db.collection.update({_id:1},{$min:{field,value}}):
根据条件返回的文档的该字段的值如果大于value,就将其更新为value,否则就保持不变 -
$max: 用法和$min类似 -
$mul:{$mul:{field1:value1,field2:value2,...}}:用法和$inc类似,将返回的文档中对应字段的数值乘以value,更新后将其返回 -
$rename:{$rename:{field:new_name}}:将返回的文档中的对应字段重新命名,并返回 -
$set:{field:value}:将返回的文档中的对应字段设置为value,并返回