MongoDB(operator)

關(guān)于operators

官方參考文檔:https://docs.mongodb.org/manual/reference/
下面會(huì)對(duì)這些operator進(jìn)行詳解,先參考如下分類(lèi):

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詳細(xì)解釋如下:

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是個(gè)數(shù)組type,那么value可以是數(shù)組中的一個(gè)元素,也可以是數(shù)組。
      
    • $lt
      功能:用于比較,意義是less than,一般用于find或update。
      用法: {field: {$lt: value} }
      例子:db.test.find( { "number": { $lt: 20 } } )
      例子效果:列出test集合中所有number<20的文檔
      注:比較操作符可以搭配組合實(shí)習(xí)區(qū)間篩選。
      
    • $gt
      功能:用于比較,意義是greater than,一般用于find或update。
      用法:{field: {$gt: value} }
      例子:db.test.find( { "age": { $gt: 20 } } )
      例子效果:列出test集合中所有age>20的文檔
      注:比較操作符可以搭配組合實(shí)習(xí)區(qū)間篩選。
      
    • $lte
      功能:用于比較,意義是less than or equal to,一般用于find或update。
      用法:{ field: { $lte: value} }
      例子:db.test.find( { "number": { $lte: 20 } } )
      例子效果:列出test集合中所有number<=20的文檔
      注:比較操作符可以搭配組合實(shí)習(xí)區(qū)間篩選。
      
    • $gte
      功能:用于比較,意義是greater than or equal to,一般用于find或update。
      用法:{field: {$gte: value} }
      例子:db.test.find( { "age": { $gte: 20 } } )
      例子效果:列出test集合中所有age>=20的文檔
      注:比較操作符可以搭配組合實(shí)習(xí)區(qū)間篩選。用于Date格式尤為合適。
      
    • $eq
      功能:用于匹配,意義是equal to,一般用于find或update。
      用法:{ <field>: { $eq: <value> } }
      例子:db.test.find( { "age": { $eq: 10086 } } )
      例子效果:精確匹配,等同于db.test.find( { "age": 10086 } )
      注:一般不用,可以簡(jiǎn)寫(xiě)。比較操作符可以搭配組合實(shí)習(xí)區(qū)間篩選。
      
    • $in
      功能:用于匹配,一般用于find或update,匹配一個(gè)數(shù)組中的任一個(gè)。
      用法:{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }
      例子:db.students.find( { "age": { $in: [ 14, 15 ] } } )
      例子效果:列出所有14、15歲的學(xué)生。
      注:別看錯(cuò)了,這個(gè)數(shù)組不是區(qū)間,并不等同于$gte搭配$ltq。
      
    • $in
      功能:用于匹配,一般用于find或update,篩出不匹配完全不匹配的文檔。
      用法:{ field: { $nin: [ <value1>, <value2> ... <valueN> ]} }
      例子:db.students.find( { "age": { $in: [ 17, 18, 19 ] } } )
      例子效果:列出所有非17、18歲、19歲的學(xué)生,不允許他們參加高考。
      注:
      
  • Logical Query Operators

    • $or
      功能:邏輯或,用于匹配,只要有一個(gè)field匹配中的就滿(mǎn)足條件,一般用于find或update。
      用法:{ $or: [ { <expression1> }, { <expression2> }, ...  } ] }
      例子:db.goods.find( { $or: [ { quality: { $gt: 20 } }, { price: 10 } ] } )
      例子效果:挑出那些要么質(zhì)量好的,要么價(jià)格便宜的商品。
      注:每個(gè)expression的限制程度應(yīng)該升序,這樣余下的篩選工作才會(huì)更快。
      
    • $and
      功能:邏輯與,用于匹配,選中所有field都匹配的文檔,一般用于find或update。
      用法:{ $and: [ { <expression1> }, { <expression2> } , ...  } ] }
      例子:db.goods.find( { $and: [ { price: 2.0 }, { city: "Beijing" } ] } )
      例子效果:列出要在北京能夠以2塊錢(qián)買(mǎi)得到的東西。
      注:每個(gè)expression的限制程度應(yīng)該降序,這樣大部分就已經(jīng)被忽略了。
      
    • $not
      功能:邏輯反,用于匹配,搜到那些不匹配的文檔,一般用于find或update。
      用法:{ field: { $not: { <operator-expression> } } }
      例子:db.test.find( { price: { $not: { $gt: 1.99 } } } )
      例子效果:$not和$gt搭配,相當(dāng)于<=號(hào)。價(jià)格在1.99以上的被選中。
      注:不能與$regex搭配使用,而是用/xxx/來(lái)使用正則,如find( { item: { $not: /^p.*/ } } )。
      
    • $nor
      功能:選中那些全部expression都不匹配的文檔。
      用法:{ $nor: [ { <expression1> }, { <expression2> }, ...  ] }
      例子:db.people.find( { $nor: [ { body: "fat" }, { hair: "black" } ] } )
      例子效果:選一些古惑仔去打架,黑頭發(fā)和太胖的就不行啦。
      注:只要文檔匹配到任意一個(gè),都不會(huì)被選中。
      
  • Element Query Operators

    • $exist
      功能:過(guò)濾掉指定field是存在or不存在的文檔。
      用法:{ field: { $exists: <boolean> } }
      例子:db.inventory.find( { "num": { $exists: true } } )
      例子效果:只查詢(xún)具有num域的文檔,包括該域?yàn)閚ull的文檔。
      注:true為必須存在字段,false在必須不存在。
      
    • $type
      功能:類(lèi)型匹配,查詢(xún)時(shí)可指定搜索域的類(lèi)型,可避免亂七八糟的類(lèi)型。
      用法:{ field: { $type: <BSON type number> | <String alias> } }
      例子1:db.addressBook.find( { "zipCode" : { $type : 1 } } )
      例子2:db.addressBook.find( { "zipCode" : { $type : "double" } } )
      例子效果:都是只考慮那些zipCode類(lèi)型為double的文檔。
      注:關(guān)于array類(lèi)型有些注意點(diǎn)。number類(lèi)型可以通指。
      
  • Evaluation Query Operators

    • $mod
      功能:取模操作,并指定取模結(jié)果來(lái)返回文檔,一般用于find。
      用法:{ field: { $mod: [ divisor, remainder ] } }
      例子:db.test.find( { number: { $mod: [ 4, 0 ] } } )
      例子效果:選中number域中的值除以4余0的文檔。
      注:
      
    • $regex
      功能:使用正則表達(dá)式進(jìn)行匹配,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
      功能:指定要匹配的是字符串,提供匹配的高級(jí)操作。
      用法:
      { 
        $text: { 
          $search: <string>, 
          $language: <string>, 
          $caseSensitive: <boolean>, 
          $diacriticSensitive: <boolean> 
        }
      }
      注:字符串匹配操作比較復(fù)雜,參考官網(wǎng)。
      
    • $where
      功能:指定同個(gè)文檔內(nèi)的兩個(gè)field進(jìn)行比較,以進(jìn)行特殊的篩選。
      用法1:db.myCollection.find( { $where: "this.credits == this.debits" } )  省略function寫(xiě)法。
      用法2:db.myCollection.find( { $where: function() { return (this.credits == this.debits) } }   
      用法3:db.myCollection.find( "this.credits == this.debits || this.credits > this.debits" )  當(dāng)篩選條件僅有一個(gè)$where表達(dá)式時(shí)。
      用法4:db.myCollection.find( function() { return (this.credits == this.debits || this.credits > this.debits ) } )  當(dāng)篩選條件僅有一個(gè)$where表達(dá)式時(shí)。
      注:若返回true則選中該文檔。
      
  • Geospatial Query Operators

    • 二維相關(guān)的查詢(xún),暫時(shí)略。
  • Query Operator Array

    • $all
      功能:用于數(shù)組匹配,可以指定數(shù)組中必須包含的元素。
      用法:{ <field>: { $all: [ <value1> , <value2> ... ] } }
      例子:{ "money": { $all: [ 5 , 2 , 1 ] } }
      例子效果:想找10塊錢(qián)零錢(qián),找同時(shí)有散錢(qián)1、2、5的人。
      注:指定的value并沒(méi)有先后順序,只檢測(cè)包含性,所以有多個(gè)也沒(méi)有關(guān)系。
      
    • $elemMatch(query)
      功能:匹配內(nèi)嵌文檔或數(shù)組中的部分field。
      用法:{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }
      例子:db.scores.find( { results: { $elemMatch: { $gte: 80, $lt: 85 } } })
      例子效果:對(duì)于那些results數(shù)組中具有區(qū)間[80,85)元素的文檔選中。
      注:
      
    • $size
      功能:指定數(shù)組的大小。
      用法:db.collection.find( { <field>: { $size: <n> } } );
      例子:db.people.find( { "card": { $size: 5 } } );
      例子效果:集齊全5張卡片才能兌換禮品。
      注:不能與$gt等比較操作符搭配。具體見(jiàn)官網(wǎng)。
      
  • Bitwise Query Operators
  • Projection Operators
    • $(projection)
      功能:對(duì)array取下標(biāo)。
      用法:db.collection.find( { <array.field>: <value> ...}, { "<array>.$": 1 } )
      例子:db.students.find( { grades: { $gte: 85 } }, { "grades.$": 1 } )
      例子效果:將選中文檔中首個(gè)大于等于85的數(shù)返回。
      注:不能暴力使用多個(gè)array,提倡用$eleMatch。
      
    • $elemMatch(projection)
      功能:用于數(shù)組中的元素匹配,可用于find的第2個(gè)參數(shù)。
      用法:
      例子:db.schools.find( { zipcode: "63109" }, { students: { $elemMatch: { school: 102, age: { $gt: 10} } } } )
      例子效果:第2個(gè)參數(shù)是決定要返回的field的。
      注:看官網(wǎng)吧。
      
    • $meta
      功能:取出$text匹配的文檔分?jǐn)?shù),看text了解score的概念就懂了。
      用法:{ $meta: <metaDataKeyword> }
      例子:db.collection.find( {$text: { $search: "coffee bake" } }, { score: { $meta: "textScore" } })
      例子效果:cofee bake兩個(gè)單詞的匹配工作會(huì)使得每個(gè)文檔得到一個(gè)分?jǐn)?shù),$meta調(diào)出這個(gè)分?jǐn)?shù)。
      注:要配合$text來(lái)使用,僅用于字符串搜索。
      
    • $slice(projection)
      功能:在查詢(xún)中將數(shù)組進(jìn)行切片。
      用法:{ <array>: {$slice: <count-expression> } }
      例子:db.posts.find( {_id:1}, { comments: { $slice: [23, 5] } } )
      例子效果:顯示id=1的整個(gè)文檔,但其中comments數(shù)組僅顯示從第24開(kāi)始的5個(gè)元素。
      注:<count-expression>有多種方式:<n>表前n個(gè)、<-n>表后n個(gè)、<[begin, n]>從下標(biāo)begin開(kāi)始的n個(gè)、<[-begin, n]>忽略掉后begin個(gè)再取后n個(gè)。
      

Update Operators

一個(gè)field可以有多個(gè)查詢(xún)條件限制,但不能夠?qū)?yīng)多個(gè)修改器。如下都是修改器。

  • Field Update Operators

    • $inc
      功能:將文檔中的某個(gè)field對(duì)應(yīng)的value自增/減某個(gè)數(shù)字amount,是原子操作。
      用法:{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
      例子:db.products.update( { _id: 1 }, { $inc: { quantity: -2} })
      例子效果:將id=1的文檔的quanty項(xiàng)自減2。
      注:只允許操作數(shù)字型field(如浮點(diǎn),整型),否則報(bào)錯(cuò)。若不存在field,則創(chuàng)建并初始化為0后再操作。
      
    • $mul
      功能:將文檔內(nèi)的指定域作乘法,是原子操作。
      用法:{ $mul: { field: <number> } }
      例子:db.products.update( { _id: 1 }, { $mul: { price: 1.25 } })
      例子效果:將_id=1的文檔中的price域的值乘以1.25。
      注:若沒(méi)有指定的field,將創(chuàng)建一個(gè)再賦值為0值。會(huì)涉及數(shù)值類(lèi)型轉(zhuǎn)化。
      
    • $rename
      功能:更改已存在的文檔的指定field名稱(chēng)。
      用法:{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }
      例子:db.students.update( { _id: 1 }, { $rename: { 'cell': 'mobile' } } )
      例子效果:將cell域名改成了mobile。
      注:其實(shí)使用了$unset和$set。
      
    • $setOnInsert
      功能:配合upsert操作,在作為insert時(shí)可以為新文檔擴(kuò)展更多的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"項(xiàng)修改為worker。
      注:若field不存在,則創(chuàng)建。若field中包含dot,則會(huì)創(chuàng)建一個(gè)內(nèi)嵌文檔再填充。
      
    • $unset
      功能:刪除文檔中的某個(gè)項(xiàng),同樣可刪內(nèi)嵌型。
      用法:{ $unset: { <field1>: "", ... } }
      例子:db.products.update( { _id: 1 }, { $unset: { quantity: "", instock: "" } })
      例子效果:刪除掉了id=1的文檔的兩個(gè)key。
      注:若文檔中不存在field項(xiàng),則不操作。
      
    • $min
      功能:更新一個(gè)field要么為指定的值,要么是不變,取決于其中的小者。
      用法:{ $min: { <field1>: <value1>, ... } }
      例子:db.scores.update( { _id: 1 }, { $min: { lowScore: 150 } } )
      例子效果:假設(shè)_id=1的文檔中的lowScore的值為200,那么它立刻被更新為150。
      注:保證指定field的值小于等于我指定的值。
      
    • $max
      功能:與$min相反。
      注:
      
    • $currentDate
      功能: 設(shè)置指定field值為當(dāng)前的時(shí)間。
      用法:{ $currentDate: { <field1>: <typeSpecification1>, ... } }
      例子:db.users.update( { _id: 1 }, { $currentDate: { "lastLogin": { $type: "timestamp" } } })
      例子效果:直接修改了lastLogin為當(dāng)前時(shí)間戳。
      注:日期可以是Date()也可以是timestamp。
      
  • Array Update Operators

    • $(update)
      功能:定位符'$',可獲取元素在array中的下標(biāo)(從0開(kāi)始),一般用于update。
      用法:{ "<array>.$" : value }
      例子:db.students.update( { _id: 1, grades: 80 }, { $set: { "grades.$" : 82 } })
      例子效果:將id=1的文檔中的grades數(shù)組中的元素80搜出來(lái),獲取其在數(shù)組中的下標(biāo),以此為索引來(lái)更新元素為82。
      注:使用在其他地方有諸多限制,參考官方文檔。
      
    • $addToSet
      功能:用于更新,添加一個(gè)value到一個(gè)array中,一般用于update第2個(gè)參數(shù)。
      用法:{ $addToSet: {<field1>: <value1>, ...} }
      例子:db.test.update( { "age":  20}, {$addToSet: { "email": "new@qq.com" }} )
      例子效果:將新郵箱插入到test集合中的所有age=20的文檔中的email數(shù)組中的末尾。
      注:field只可以是array類(lèi)型。在update時(shí),若field不存在,則創(chuàng)建,若value已存在,則不操作。
         需要注意的是同時(shí)插入多個(gè)value于同一array的情況,要么每次都寫(xiě)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的加強(qiáng)版,可以一次性保證多個(gè)元素不在數(shù)組中。
      用法:{ $pullAll: { <field1>: [ <value1>, <value2> ... ], ... } }
      例子:db.survey.update( { _id: 1 }, { $pullAll: { scores: [ 0, 5 ] } } )
      例子效果:保證了指定文檔中scores數(shù)組不包含0和5。
      注:可以充當(dāng)pull使用,也可以搭配使用。
      
    • $pull
      功能:刪除滿(mǎn)足條件的數(shù)組元素。
      用法:{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }
      例子:db.stores.update( { }, { $pull: {vegetables: "carrots" } })
      例子效果:保證stores集合中所有文檔中的vegetables數(shù)組不含單詞"carrots"。
      注:所有條件都匹配中了就刪除。而欲刪除array中的集合,則需指定完全匹配的集合。condition可以指定條件。
      
    • $pushAll
      功能:$push的加強(qiáng)版,可往一個(gè)數(shù)字中塞更多的元素。
      用法:{ $pushAll: { <field>: [ <value1>, <value2>, ... ] } }
      例子:同$pullAll
      注:指定單個(gè)value時(shí)就變成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 等等來(lái)使用。注意大量push時(shí)的效率。
      
    • $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個(gè)單詞。
      用法2:{ $push: { <array>: { $each: [ <value1>, <value2> ... ] } } }
      例子2:db.students.update( { name: "joe" }, { $push: { scores: { $each: [ 90, 92, 85 ] } } })
      例子2效果:在students集合中的name="joe"的所有文檔都添加3個(gè)數(shù)字進(jìn)scores數(shù)組。
      注:若存在,則不插入,否則插入進(jìn)數(shù)組。
      
    • $slice
      功能:配合$each在$push之后,對(duì)擴(kuò)充的數(shù)組進(jìn)行切片。
      用法:{ $push: { <field>: { $each: [ <value1>, <value2>, ... ], $slice: <num> } }}
      例子:db.students.update( { _id: 1 }, { $push: { scores: { $each: [ 80, 78, 86 ], $slice: -5 } } })
      例子效果:往scores插入了3個(gè)數(shù)字后,只留下數(shù)組中的后5個(gè)元素,其他刪除。
      注:作用比較特殊,可以用來(lái)保證數(shù)組中至少有多少個(gè)元素?
      
    • $sort
      功能:配合$each在$push中使用,在push一些元素進(jìn)數(shù)組之后可以對(duì)數(shù)組進(jìn)行排序。
      用法:{ $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個(gè)文檔,再按照score進(jìn)行排序。
      注:作為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個(gè)元素。
      注:
      
  • Bitwise Update Operators

    • $bit
      功能:
      用法:{ $bit: { <field>: { <and|or|xor>: <int> } } }
      例子:db.switches.update( { _id: 1 }, { $bit: { expdata: { and: NumberInt(10) } } })
      例子效果:對(duì)expdata域的值作按位與操作。
      注:操作數(shù)只能是32位或64位整數(shù)。而mongo shell中的數(shù)字都是double型的,注意轉(zhuǎn)。
      
  • Isolation Update Operators

    • $isolated
      功能:對(duì)多文檔的write操作保持一致性,杜絕無(wú)處理一半的情況出現(xiàn)。
      用法:{ <query> , $isolated : 1 }
      例子:db.foo.update( { status : "A" , $isolated : 1 }, { $inc : { count : 1 } }, { multi: true })
      例子效果:修改多個(gè)選中的文檔,在修改完成之前其他的client看不到任何變化。
      注:不能用于shard cluster。會(huì)使得WiredTiger變成單線(xiàn)程,影響并發(fā)性。不提供all-or-nothing。
      

Aggregation Pipeline Operators

  • Pipeline Aggregation Stages
    • $project

      功能:
      用法:{ $project: { <specifications> } }
      例子:
      例子效果:
      注:id域是默認(rèn)輸出的,指定不存在的field會(huì)被忽略。
      
    • $match $redact $limit $skip $unwind $group $sample $sort $geoNear $lookup $out $indexStats 這些還未整理。


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容