關于operators
官方參考文檔:https://docs.mongodb.org/manual/reference/
下面會對這些operator進行詳解挖函,先參考如下分類:
Query and Projection Operators
- Comparison Query Operators 例如:$eq $gt $gte $lt $lte $ne $in $nin
- Logical Query Operators 例如:$or $and $not $nor
- Element Query Operators 例如:$exist $type
- Evaluation Query Operators 例如:$mod $regex $text $where
- Geospatial Query Operators
- Query Operator Array 例如:$all $elemMatch(query) $size
- Bitwise Query Operators 例如:$bitsAllSet $bitsAnySet $bitsAllClear $bitsAnyClear
- Projection Operators 例如:$(projection) $elemMatch(projection) $meta $slice(projection)
Update Operators
- Field Update Operators 例如:$inc $mul $rename $setOnInsert $set $unset $min $max $currentDate
- Array Update Operators 例如:$(update) $addToSet $pop $pullAll $pull $pushAll $push $each $slice $sort $position
- Bitwise Update Operators 例如:$bit
- Isolation Update Operators 例如:$isolated
Aggregation Pipeline Operators
- Pipeline Aggregation Stages 例如:$project $match $redact $limit $skip $unwind $group $sample $sort $geoNear $lookup $out $indexStats
- Boolean Aggregation Operators
- Set Operators (Aggregation)
- Comparison Aggregation Operators
- Arithmetic Aggregation Operators
- String Aggregation Operators
- Text Search Aggregation Operators
- Array Aggregation Operators
- Aggregation Variable Operators
- Aggregation Literal Operators
- Date Aggregation Operators
- Conditional Aggregation Operators
- Group Accumulator Operators
Operators詳細解釋如下:
Query and Projection Operators
-
Comparison Query Operators
- $ne
功能:用于比較,意義是not equal to瓢姻,一般用于find或update。 用法:{field: {$ne: value}} 例子:db.test.find({ "age": {$ne: 20} }) 例子效果:列出test集合中所有age不等于20的文檔 注:如果field是個數(shù)組type延塑,那么value可以是數(shù)組中的一個元素巩掺,也可以是數(shù)組。
- $lt
功能:用于比較页畦,意義是less than,一般用于find或update研儒。 用法: {field: {$lt: value} } 例子:db.test.find( { "number": { $lt: 20 } } ) 例子效果:列出test集合中所有number<20的文檔 注:比較操作符可以搭配組合實習區(qū)間篩選豫缨。
- $gt
功能:用于比較,意義是greater than端朵,一般用于find或update好芭。 用法:{field: {$gt: value} } 例子:db.test.find( { "age": { $gt: 20 } } ) 例子效果:列出test集合中所有age>20的文檔 注:比較操作符可以搭配組合實習區(qū)間篩選。
- $lte
功能:用于比較冲呢,意義是less than or equal to舍败,一般用于find或update。 用法:{ field: { $lte: value} } 例子:db.test.find( { "number": { $lte: 20 } } ) 例子效果:列出test集合中所有number<=20的文檔 注:比較操作符可以搭配組合實習區(qū)間篩選敬拓。
- $gte
功能:用于比較邻薯,意義是greater than or equal to,一般用于find或update乘凸。 用法:{field: {$gte: value} } 例子:db.test.find( { "age": { $gte: 20 } } ) 例子效果:列出test集合中所有age>=20的文檔 注:比較操作符可以搭配組合實習區(qū)間篩選厕诡。用于Date格式尤為合適。
- $eq
功能:用于匹配营勤,意義是equal to灵嫌,一般用于find或update。 用法:{ <field>: { $eq: <value> } } 例子:db.test.find( { "age": { $eq: 10086 } } ) 例子效果:精確匹配葛作,等同于db.test.find( { "age": 10086 } ) 注:一般不用寿羞,可以簡寫。比較操作符可以搭配組合實習區(qū)間篩選赂蠢。
- $in
功能:用于匹配绪穆,一般用于find或update,匹配一個數(shù)組中的任一個客年。 用法:{ field: { $in: [<value1>, <value2>, ... <valueN> ] } } 例子:db.students.find( { "age": { $in: [ 14, 15 ] } } ) 例子效果:列出所有14霞幅、15歲的學生。 注:別看錯了量瓜,這個數(shù)組不是區(qū)間司恳,并不等同于$gte搭配$ltq。
- $in
功能:用于匹配绍傲,一般用于find或update扔傅,篩出不匹配完全不匹配的文檔耍共。 用法:{ field: { $nin: [ <value1>, <value2> ... <valueN> ]} } 例子:db.students.find( { "age": { $in: [ 17, 18, 19 ] } } ) 例子效果:列出所有非17、18歲猎塞、19歲的學生试读,不允許他們參加高考。 注:
- $ne
-
Logical Query Operators
- $or
功能:邏輯或荠耽,用于匹配钩骇,只要有一個field匹配中的就滿足條件,一般用于find或update铝量。 用法:{ $or: [ { <expression1> }, { <expression2> }, ... } ] } 例子:db.goods.find( { $or: [ { quality: { $gt: 20 } }, { price: 10 } ] } ) 例子效果:挑出那些要么質量好的倘屹,要么價格便宜的商品。 注:每個expression的限制程度應該升序慢叨,這樣余下的篩選工作才會更快纽匙。
- $and
功能:邏輯與,用于匹配拍谐,選中所有field都匹配的文檔烛缔,一般用于find或update。 用法:{ $and: [ { <expression1> }, { <expression2> } , ... } ] } 例子:db.goods.find( { $and: [ { price: 2.0 }, { city: "Beijing" } ] } ) 例子效果:列出要在北京能夠以2塊錢買得到的東西。 注:每個expression的限制程度應該降序,這樣大部分就已經被忽略了跃脊。
- $not
功能:邏輯反统诺,用于匹配,搜到那些不匹配的文檔,一般用于find或update。 用法:{ field: { $not: { <operator-expression> } } } 例子:db.test.find( { price: { $not: { $gt: 1.99 } } } ) 例子效果:$not和$gt搭配,相當于<=號崖面。價格在1.99以上的被選中。 注:不能與$regex搭配使用梯影,而是用/xxx/來使用正則巫员,如find( { item: { $not: /^p.*/ } } )。
- $nor
功能:選中那些全部expression都不匹配的文檔甲棍。 用法:{ $nor: [ { <expression1> }, { <expression2> }, ... ] } 例子:db.people.find( { $nor: [ { body: "fat" }, { hair: "black" } ] } ) 例子效果:選一些古惑仔去打架简识,黑頭發(fā)和太胖的就不行啦。 注:只要文檔匹配到任意一個感猛,都不會被選中七扰。
- $or
-
Element Query Operators
- $exist
功能:過濾掉指定field是存在or不存在的文檔。 用法:{ field: { $exists: <boolean> } } 例子:db.inventory.find( { "num": { $exists: true } } ) 例子效果:只查詢具有num域的文檔陪白,包括該域為null的文檔颈走。 注:true為必須存在字段,false在必須不存在咱士。
- $type
功能:類型匹配立由,查詢時可指定搜索域的類型轧钓,可避免亂七八糟的類型。 用法:{ field: { $type: <BSON type number> | <String alias> } } 例子1:db.addressBook.find( { "zipCode" : { $type : 1 } } ) 例子2:db.addressBook.find( { "zipCode" : { $type : "double" } } ) 例子效果:都是只考慮那些zipCode類型為double的文檔锐膜。 注:關于array類型有些注意點毕箍。number類型可以通指。
- $exist
-
Evaluation Query Operators
- $mod
功能:取模操作道盏,并指定取模結果來返回文檔而柑,一般用于find。 用法:{ field: { $mod: [ divisor, remainder ] } } 例子:db.test.find( { number: { $mod: [ 4, 0 ] } } ) 例子效果:選中number域中的值除以4余0的文檔荷逞。 注:
- $regex
功能:使用正則表達式進行匹配牺堰,3種使用方式有各自的限制。 用法1:{ <field>: { $regex: /pattern/, $options: '<options>' } } 用法2:{ <field>: { $regex: 'pattern', $options: '<options>' } } 用法3:{ <field>: { $regex: /pattern/<options> } } 例子: 例子效果: 注:<options>的參數(shù)很多颅围,比如 i m x s 。
- $text
功能:指定要匹配的是字符串恨搓,提供匹配的高級操作院促。 用法: { $text: { $search: <string>, $language: <string>, $caseSensitive: <boolean>, $diacriticSensitive: <boolean> } } 注:字符串匹配操作比較復雜,參考官網斧抱。
- $where
功能:指定同個文檔內的兩個field進行比較常拓,以進行特殊的篩選。 用法1:db.myCollection.find( { $where: "this.credits == this.debits" } ) 省略function寫法辉浦。 用法2:db.myCollection.find( { $where: function() { return (this.credits == this.debits) } } 用法3:db.myCollection.find( "this.credits == this.debits || this.credits > this.debits" ) 當篩選條件僅有一個$where表達式時弄抬。 用法4:db.myCollection.find( function() { return (this.credits == this.debits || this.credits > this.debits ) } ) 當篩選條件僅有一個$where表達式時。 注:若返回true則選中該文檔宪郊。
- $mod
-
Geospatial Query Operators
- 二維相關的查詢掂恕,暫時略。
-
Query Operator Array
- $all
功能:用于數(shù)組匹配弛槐,可以指定數(shù)組中必須包含的元素懊亡。 用法:{ <field>: { $all: [ <value1> , <value2> ... ] } } 例子:{ "money": { $all: [ 5 , 2 , 1 ] } } 例子效果:想找10塊錢零錢,找同時有散錢1乎串、2店枣、5的人。 注:指定的value并沒有先后順序叹誉,只檢測包含性鸯两,所以有多個也沒有關系。
- $elemMatch(query)
功能:匹配內嵌文檔或數(shù)組中的部分field长豁。 用法:{ <field>: { $elemMatch: { <query1>, <query2>, ... } } } 例子:db.scores.find( { results: { $elemMatch: { $gte: 80, $lt: 85 } } }) 例子效果:對于那些results數(shù)組中具有區(qū)間[80,85)元素的文檔選中钧唐。 注:
- $size
功能:指定數(shù)組的大小。 用法:db.collection.find( { <field>: { $size: <n> } } ); 例子:db.people.find( { "card": { $size: 5 } } ); 例子效果:集齊全5張卡片才能兌換禮品蕉斜。 注:不能與$gt等比較操作符搭配逾柿。具體見官網缀棍。
- $all
- Bitwise Query Operators
- Projection Operators
- $(projection)
功能:對array取下標。 用法:db.collection.find( { <array.field>: <value> ...}, { "<array>.$": 1 } ) 例子:db.students.find( { grades: { $gte: 85 } }, { "grades.$": 1 } ) 例子效果:將選中文檔中首個大于等于85的數(shù)返回机错。 注:不能暴力使用多個array爬范,提倡用$eleMatch。
- $elemMatch(projection)
功能:用于數(shù)組中的元素匹配弱匪,可用于find的第2個參數(shù)青瀑。 用法: 例子:db.schools.find( { zipcode: "63109" }, { students: { $elemMatch: { school: 102, age: { $gt: 10} } } } ) 例子效果:第2個參數(shù)是決定要返回的field的。 注:看官網吧萧诫。
- $meta
功能:取出$text匹配的文檔分數(shù)斥难,看text了解score的概念就懂了。 用法:{ $meta: <metaDataKeyword> } 例子:db.collection.find( {$text: { $search: "coffee bake" } }, { score: { $meta: "textScore" } }) 例子效果:cofee bake兩個單詞的匹配工作會使得每個文檔得到一個分數(shù)帘饶,$meta調出這個分數(shù)哑诊。 注:要配合$text來使用,僅用于字符串搜索及刻。
- $slice(projection)
功能:在查詢中將數(shù)組進行切片镀裤。 用法:{ <array>: {$slice: <count-expression> } } 例子:db.posts.find( {_id:1}, { comments: { $slice: [23, 5] } } ) 例子效果:顯示id=1的整個文檔,但其中comments數(shù)組僅顯示從第24開始的5個元素缴饭。 注:<count-expression>有多種方式:<n>表前n個暑劝、<-n>表后n個、<[begin, n]>從下標begin開始的n個颗搂、<[-begin, n]>忽略掉后begin個再取后n個担猛。
- $(projection)
Update Operators
一個field可以有多個查詢條件限制,但不能夠對應多個修改器丢氢。如下都是修改器傅联。
-
Field Update Operators
- $inc
功能:將文檔中的某個field對應的value自增/減某個數(shù)字amount,是原子操作疚察。 用法:{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } } 例子:db.products.update( { _id: 1 }, { $inc: { quantity: -2} }) 例子效果:將id=1的文檔的quanty項自減2纺且。 注:只允許操作數(shù)字型field(如浮點,整型)稍浆,否則報錯载碌。若不存在field,則創(chuàng)建并初始化為0后再操作衅枫。
- $mul
功能:將文檔內的指定域作乘法嫁艇,是原子操作。 用法:{ $mul: { field: <number> } } 例子:db.products.update( { _id: 1 }, { $mul: { price: 1.25 } }) 例子效果:將_id=1的文檔中的price域的值乘以1.25弦撩。 注:若沒有指定的field步咪,將創(chuàng)建一個再賦值為0值。會涉及數(shù)值類型轉化益楼。
- $rename
功能:更改已存在的文檔的指定field名稱猾漫。 用法:{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } } 例子:db.students.update( { _id: 1 }, { $rename: { 'cell': 'mobile' } } ) 例子效果:將cell域名改成了mobile点晴。 注:其實使用了$unset和$set。
- $setOnInsert
功能:配合upsert操作悯周,在作為insert時可以為新文檔擴展更多的field粒督。 用法:db.collection.update( <query>, { $setOnInsert: { <field1>: <value1>, ... } }, { upsert: true }) 例子:db.products.update( { _id: 1 }, { $set: { item: "apple" }, $setOnInsert: { money: 100 } }, { upsert: true }) 例子效果:若_id=1的文檔存在,僅改item禽翼,否則插入由item域和$setOnInsert所指定的域組成的文檔屠橄。 注:
- $set
功能:文檔中value的替換,一般用于update闰挡。 用法:{ $set: { <field1>: <value1>, ... } } 例子:db.stuff.update( { _id: 100 }, { $set: { "job": "worker"} }) 例子效果:將id=100的文檔的"job"項修改為worker锐墙。 注:若field不存在,則創(chuàng)建长酗。若field中包含dot溪北,則會創(chuàng)建一個內嵌文檔再填充。
- $unset
功能:刪除文檔中的某個項夺脾,同樣可刪內嵌型刻盐。 用法:{ $unset: { <field1>: "", ... } } 例子:db.products.update( { _id: 1 }, { $unset: { quantity: "", instock: "" } }) 例子效果:刪除掉了id=1的文檔的兩個key。 注:若文檔中不存在field項劳翰,則不操作。
- $min
功能:更新一個field要么為指定的值馒疹,要么是不變佳簸,取決于其中的小者。 用法:{ $min: { <field1>: <value1>, ... } } 例子:db.scores.update( { _id: 1 }, { $min: { lowScore: 150 } } ) 例子效果:假設_id=1的文檔中的lowScore的值為200,那么它立刻被更新為150颖变。 注:保證指定field的值小于等于我指定的值生均。
- $max
功能:與$min相反。 注:
- $currentDate
功能: 設置指定field值為當前的時間腥刹。 用法:{ $currentDate: { <field1>: <typeSpecification1>, ... } } 例子:db.users.update( { _id: 1 }, { $currentDate: { "lastLogin": { $type: "timestamp" } } }) 例子效果:直接修改了lastLogin為當前時間戳马胧。 注:日期可以是Date()也可以是timestamp。
- $inc
-
Array Update Operators
- $(update)
功能:定位符'$'衔峰,可獲取元素在array中的下標(從0開始)佩脊,一般用于update。 用法:{ "<array>.$" : value } 例子:db.students.update( { _id: 1, grades: 80 }, { $set: { "grades.$" : 82 } }) 例子效果:將id=1的文檔中的grades數(shù)組中的元素80搜出來垫卤,獲取其在數(shù)組中的下標威彰,以此為索引來更新元素為82。 注:使用在其他地方有諸多限制穴肘,參考官方文檔歇盼。
- $addToSet
功能:用于更新,添加一個value到一個array中评抚,一般用于update第2個參數(shù)豹缀。 用法:{ $addToSet: {<field1>: <value1>, ...} } 例子:db.test.update( { "age": 20}, {$addToSet: { "email": "new@qq.com" }} ) 例子效果:將新郵箱插入到test集合中的所有age=20的文檔中的email數(shù)組中的末尾伯复。 注:field只可以是array類型。在update時邢笙,若field不存在啸如,則創(chuàng)建,若value已存在鸣剪,則不操作组底。 需要注意的是同時插入多個value于同一array的情況,要么每次都寫field域筐骇,要么使用$each债鸡。
- $pop
功能:刪除array的首元素或尾元素,一般用于update铛纬。 用法:{ $pop: { <field>: <-1 | 1>, ... } } 例子:db.students.update( { _id: 1 }, { $pop: { scores: -1 } } ) 例子效果:刪除id=1的文檔中scores數(shù)組的首元素厌均。 注:-1和1分別表示首、尾的意思告唆。
- $pullAll
功能:pull的加強版棺弊,可以一次性保證多個元素不在數(shù)組中。 用法:{ $pullAll: { <field1>: [ <value1>, <value2> ... ], ... } } 例子:db.survey.update( { _id: 1 }, { $pullAll: { scores: [ 0, 5 ] } } ) 例子效果:保證了指定文檔中scores數(shù)組不包含0和5擒悬。 注:可以充當pull使用模她,也可以搭配使用。
- $pull
功能:刪除滿足條件的數(shù)組元素懂牧。 用法:{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } } 例子:db.stores.update( { }, { $pull: {vegetables: "carrots" } }) 例子效果:保證stores集合中所有文檔中的vegetables數(shù)組不含單詞"carrots"侈净。 注:所有條件都匹配中了就刪除。而欲刪除array中的集合僧凤,則需指定完全匹配的集合畜侦。condition可以指定條件。
- $pushAll
功能:$push的加強版躯保,可往一個數(shù)字中塞更多的元素旋膳。 用法:{ $pushAll: { <field>: [ <value1>, <value2>, ... ] } } 例子:同$pullAll 注:指定單個value時就變成push了。
- $push
功能:往array中暴力添加元素途事,用于update验懊。 用法:{ $push: { <field1>: <value1>, ... } } 例子:db.students.update( { _id: 1 }, { $push: { scores: 89 } }) 例子效果:在students集合中的id=1的文檔中的scores數(shù)組中添加數(shù)字89。 注:如果不存在field尸变,則創(chuàng)建鲁森。可以搭配 $each $sort $slice 等等來使用振惰。注意大量push時的效率歌溉。
- $each
功能:保證數(shù)組中必定存在某些元素,搭配$addToSet或$push使用。 用法1:{ $addToSet: { <array>: { $each: [ <value1>, <value2> ... ] } } } 例子1:db.test.update( { _id: 2 }, { $addToSet: { tags: { $each: [ "camera", "electronics", "accessories" ] } } } ) 例子1效果:在test集合中的id=2的文檔的key=tags的value中添加3個單詞痛垛。 用法2:{ $push: { <array>: { $each: [ <value1>, <value2> ... ] } } } 例子2:db.students.update( { name: "joe" }, { $push: { scores: { $each: [ 90, 92, 85 ] } } }) 例子2效果:在students集合中的name="joe"的所有文檔都添加3個數(shù)字進scores數(shù)組草慧。 注:若存在,則不插入匙头,否則插入進數(shù)組漫谷。
- $slice
功能:配合$each在$push之后,對擴充的數(shù)組進行切片蹂析。 用法:{ $push: { <field>: { $each: [ <value1>, <value2>, ... ], $slice: <num> } }} 例子:db.students.update( { _id: 1 }, { $push: { scores: { $each: [ 80, 78, 86 ], $slice: -5 } } }) 例子效果:往scores插入了3個數(shù)字后舔示,只留下數(shù)組中的后5個元素,其他刪除电抚。 注:作用比較特殊惕稻,可以用來保證數(shù)組中至少有多少個元素?
- $sort
功能:配合$each在$push中使用蝙叛,在push一些元素進數(shù)組之后可以對數(shù)組進行排序俺祠。 用法:{ $push: { <field>: { $each: [ <value1>, <value2>, ... ], $sort: <sort specification> } }} 例子:db.students.update( { _id: 1 }, { $push: { quizzes: { $each: [ { id: 3, score: 8 }, { id: 4, score: 7 }, { id: 5, score: 6 } ], $sort: { score: 1 } } } }) 例子效果:數(shù)組中插入了3個文檔,再按照score進行排序借帘。 注:作為push的修改器蜘渣。
- $position
功能:配合$each在$push中使用,指定push一些元素到數(shù)組中的位置肺然。 用法:{ $push: { <field>: { $each: [ <value1>, <value2>, ... ], $position: <num> } }} 例子:db.students.update( { _id: 1 }, { $push: { scores: { $each: [ 50, 60, 70 ], $position: 0 } } }) 例子效果:往數(shù)組scores的最前端插入3個元素蔫缸。 注:
- $(update)
-
Bitwise Update Operators
- $bit
功能: 用法:{ $bit: { <field>: { <and|or|xor>: <int> } } } 例子:db.switches.update( { _id: 1 }, { $bit: { expdata: { and: NumberInt(10) } } }) 例子效果:對expdata域的值作按位與操作。 注:操作數(shù)只能是32位或64位整數(shù)际起。而mongo shell中的數(shù)字都是double型的拾碌,注意轉。
- $bit
-
Isolation Update Operators
- $isolated
功能:對多文檔的write操作保持一致性加叁,杜絕無處理一半的情況出現(xiàn)。 用法:{ <query> , $isolated : 1 } 例子:db.foo.update( { status : "A" , $isolated : 1 }, { $inc : { count : 1 } }, { multi: true }) 例子效果:修改多個選中的文檔唇撬,在修改完成之前其他的client看不到任何變化它匕。 注:不能用于shard cluster。會使得WiredTiger變成單線程窖认,影響并發(fā)性豫柬。不提供all-or-nothing。
- $isolated
Aggregation Pipeline Operators
- Pipeline Aggregation Stages
-
$project
功能: 用法:{ $project: { <specifications> } } 例子: 例子效果: 注:id域是默認輸出的扑浸,指定不存在的field會被忽略烧给。
$match $redact $limit $skip $unwind $group $sample $sort $geoNear $lookup $out $indexStats 這些還未整理。
-