Created
February 27, 2016 08:33
-
-
Save HellMagic/5f08c2a6b638acb2fd30 to your computer and use it in GitHub Desktop.
##mongo注意事项
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1.快速理解记忆各种操作符,怎么高效地查阅文档。 | |
比较操作符: | |
op.$gt | |
op.$gte | |
op.$lt | |
op.$lte | |
op.$eq | |
op.$ne | |
op.$in | |
op.$nin | |
语法:{field: {<比较操作符> : <conditional specific values>}} | |
逻辑操作符: | |
op.$and | |
op.$or | |
op.$nor | |
op.$not | |
语法:{<逻辑操作符> : [<condition1>, <condition2>]},但是$not操作符比较特殊,其语法格式与比较操作符类似,形如 | |
{field: {"$not": <value>}},需要注意的是使用$not会查询出field不存在的document,可以通过$exists来避免。 | |
元素操作符: | |
op.$exists: {field: {"$exists": <boolean>}} //注意会筛选出field的value是null的document | |
op.$type: {field: {"$type": "string"}} //多种mongo支持的类型,或者使用数字代表类型--具体各个数字和类型的关系可以查看文档 | |
数组操作符: | |
op.$all | |
op.$elemMatch | |
op.$size | |
语法:{field: {<数组操作符>: <conditional specific value>}} | |
投影操作符: | |
proj.$ -- 对数组投影,获取数组内满足前面查询条件的第一个元素,语法:{"arrFieldName.$":1},注意arrFieldName一定要出现在查询语句中 | |
porj.$elemMatch | |
proj.$slice | |
proj.$meta | |
投影作为查询的第二个参数 | |
Tips: 一般聚合中都会有与操作符op.xxx相对应的exp.xxx | |
2.$exist会查阅只要document里有某一个field字段即可,就算此field字段的value是null,也会被查出作为返回内容 | |
3.$not--和其他的逻辑操作符不同的是它的语法格式走的是选择操作符的语法格式,即{field: {"$not": { <operator-expression> }}},需要 | |
注意的是,使用$not不单会查出field值不匹配所给的expression表达式的值的document,而且会查出此field不存在的document。 | |
4.$all--此document的field是一个数组,并且数组的value包含$all所提供的所有值。与$in操作符不同,$in操作符只要求被匹配的fild的value | |
值(可以是一个值也可以是一个数组)中有那么一个值(如果是数组的话)出现在$in所提供的特定一组值中即可。 | |
{ tags: { $all: [ "ssl" , "security" ] } } 等价于 { $and: [ { tags: "ssl" }, { tags: "security" } ] }(注意,这里的tags是个数组 | |
,而这里用到了mongo数组的特殊查询处理方式,即如果field是个数组,但是给的匹配值是一个值而不是数组,那么将解释为数组是否包含这个 | |
值) | |
5.$elemMatch--主要匹配对象数组。匹配对象数组中的每一个对象符合$elemMatch所列出的条件。$elemMatch可以和各种操作符结合来使用,它 | |
最主要就是为了parse数组对象,比如,结合$all来使用: | |
db.inventory.find( { | |
qty: { $all: [ | |
{ "$elemMatch" : { size: "M", num: { $gt: 50} } }, | |
{ "$elemMatch" : { num : 100, color: "green" } } | |
] } | |
} ) | |
上述语句会筛选出:qty是一个数组,并且数组中存在满足两个$elemMatch所给条件的obj,比如会选出类似下面的结果: | |
{ | |
"_id" : ObjectId("5234ccb7687ea597eabee677"), | |
"code" : "efg", | |
"tags" : [ "school", "book"], | |
"qty" : [ | |
{ "size" : "S", "num" : 10, "color" : "blue" }, | |
{ "size" : "M", "num" : 100, "color" : "blue" }, //这条数据满足条件1 | |
{ "size" : "L", "num" : 100, "color" : "green" } //这条数据满足条件2 | |
] | |
} | |
{ | |
"_id" : ObjectId("52350353b2eff1353b349de9"), | |
"code" : "ijk", | |
"tags" : [ "electronics", "school" ], | |
"qty" : [ | |
{ "size" : "M", "num" : 100, "color" : "green" } //这条数据即满足条件1,又满足条件2 | |
] | |
} | |
6.以up.xxx为开头的是针对update的操作符,mongo提供了一系列好用的update操作符,比如$set,$unset,$rename等 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment