MongoDB中「$」操作符表達式匯總
MongoDB中「$」操作符表達式匯總
查詢
比較操作
$eq
語法:{ : { $eq: } }
釋義:匹配等於(=)指定值的文檔
舉例:
查詢age = 20的文檔: db.person.find( { age: { $eq: 20 } } ) 相當於: db.person.find( { age: 20 } )
$gt
語法:{: {$gt: } }
釋義:匹配大於(>)指定值的文檔
查詢age > 20的文檔 db.person.find({ age: { $gt: 20 } })
$gte
語法:{field: {$gte: value} }
釋義:匹配大於等於(>=)指定值的文檔
查詢age >= 20的文檔 db.person.find({ age: { $gte: 20 } })
$lt
語法:{field: {$lt: value} }
釋義:匹配小於(<)指定值的文檔
查詢age < 20的文檔 db.person.find({ age: { $lt: 20 } })
$lte
語法:{ field: { $lte: value} }
釋義:匹配小於等於(<=)指定值的文檔
查詢age <= 20的文檔 db.person.find({ age: { $lte: 20 } })
$ne
語法:{field: {$ne: value} }
釋義:匹配不等於(≠)指定值的文檔
查詢age ≠ 20的文檔 db.person.find({ age: { $ne: 20 } })
$in
語法:{ field: { $in: [, , … ] } }
釋義:匹配數組中的任一值
舉例:
查詢該集合中字段qty的值與數組中的任意值相等的文檔: db.inventory.find( { qty: { $in: [ 5, 15 ] } } )
$nin
語法:{ field: { $nin: [ , … ]} }
釋義:不匹配數組中的值
邏輯操作
$or
語法:{ $or: [ { }, { }, … , { } ] }
釋義:或 條件查詢
舉例:
查詢age < 20或者address是beijing的文檔: db.person.find( { $or: [ { age: { $lt: 20 } }, { address: "beijing" } ] } )
$and
語法:{ $and: [ { }, { } , … , { } ] }
釋義:與 條件查詢
$not
語法:{ field: { $not: { } } }
釋義:查詢與表達式不匹配的文檔
舉例:
查詢age不大於20的文檔: db.person.find( { age: { $not: { $gt: 20 } } } )
$nor
語法:{ $nor: [ { }, { }, … { } ] }
釋義:查詢與任一表達式都不匹配的文檔
舉例:
查詢age既不等於20,sex也不是男的文檔: db.person.find( { $nor: [ { age: 20 },{ sex: "男"} ] } )
集合字段操作 ——「存在」、「類型」
$exists
語法:{ field: { $exists: } }
釋義:查詢存在指定字段的文檔
舉例:
查詢存在phone字段的文檔: db.person.find( { phone: { $exists: true } } )
$type
語法:{ field: { $type: | } }
釋義:查詢類型為指定類型的文檔,3.2版本添加alias別名,各種類型的Number及Alias如下
舉例:
假設存在這樣一個集合:
{ "_id": 1, address: "2030 Martian Way",zipCode: "90698345"}, { "_id": 2, address: "156 Lunar Place",zipCode: 43339374}, { "_id": 3, address: "2324 Pluto Place",zipCode: NumberLong(3921412)}, { "_id": 4, address: "55 Saturn Ring", zipCode: NumberInt(88602117)}
查詢該集合中zipCode字段的數據類型為String類型的文檔:
db.addressBook.find( { "zipCode" : { $type : 2 } } ); db.addressBook.find( { "zipCode" : { $type : "string" } } );
運算操作
$mod
語法:{ field: { $mod: [ 除數, 餘數 ] } }
釋義:取余條件查詢
舉例:
查詢age字段的值除以2餘0的文檔: db.person.find( { age: { $mod: [ 2, 0 ] } } )
$regex
語法:
{ : { $regex: /pattern/, $options: ‘‘ } }
{ : { $regex: ‘pattern’, $options: ‘‘ } }
{ : { $regex: /pattern/ } }
釋義:正則表達式查詢
舉例:
db.products.find( { sku: { $regex: /^ABC/i } } )
$text
語法:
{ $text: { $search: <string>, $language: <string>, $caseSensitive: <boolean>, $diacriticSensitive: <boolean> } }
-
- $search ——關鍵詞
- $language ——語言,不支持中文!!!支持語言如下:點擊
- $caseSensitive——是否區分大小寫,默認false
- $diacriticSensitive——是否區分讀音,默認false
釋義:文本索引查詢
舉例:較為複雜,請參考官網
$where
釋義:把一個含有JavaScript表達式的字符串或者是整個JavaScript函數轉換到查詢系統中,對內嵌文檔不起作用
舉例:
db.myCollection.find( { $where: "this.credits == this.debits" } ); db.myCollection.find( { $where: function() { return obj.credits == obj.debits; } } );
數組操作
$all
語法:{ < field >: { $ all : [ < value1 > , < value2 > … ] } }
釋義:匹配文檔的數組字段中包含所有指定元素的文檔
舉例:
查詢articles集合中tags字段(是個數組)包含「ssl」和「security」的文檔(包含,但並不是全部等於) db.articles.find( { tags: { $all: [ [ "ssl", "security" ] ] } } )
$elemMatch(query)重要
語法:{ : { $elemMatch: { , , … } } }
釋義:匹配內嵌文檔或數組中的部分field
舉例:
假設現有集合:
{ _id: 1, results: [ 82, 85, 88 ] } { _id: 2, results: [ 75, 88, 89 ] }
查詢results數組中含有區間[80,85)元素的文檔(結果為第一條):
db.scores.find( { results: { $elemMatch: { $gte: 80, $lt: 85 } } })
$size
語法:{ field: { $size: }
釋義:匹配數組長度為指定大小的文檔
舉例:
查詢已經集齊了5張福卡的文檔: db.person.find({card:{$size:5}})
查詢相似document操作
$(projection)
釋義:查詢數組中首個匹配條件的元素
舉例:
假設現有如下集合students:
{ "_id" : 1, "semester" : 1, "grades" : [ 70, 87, 90 ] } { "_id" : 2, "semester" : 1, "grades" : [ 90, 88, 92 ] } { "_id" : 3, "semester" : 1, "grades" : [ 85, 100, 90 ] } { "_id" : 4, "semester" : 2, "grades" : [ 79, 85, 80 ] } { "_id" : 5, "semester" : 2, "grades" : [ 88, 88, 92 ] } { "_id" : 6, "semester" : 2, "grades" : [ 95, 90, 96 ] }
查詢semester=1,並且grades符合大於等於85的document中”grades”中字段的第一個元素:
db.students.find( { semester: 1, grades: { $gte: 85 } },{ "grades.$": 1 } )
返回如下結果:
{ "_id" : 1, "grades" : [ 87 ] }{ "_id" : 2, "grades" : [ 90 ] }{ "_id" : 3, "grades" : [ 85 ] }
$elemMatch(projection)
釋義:用於數組或內嵌文檔中的元素匹配(子元素匹配),只會返回匹配的第一個元素!!!
舉例:
假設現有如下集合:
{ _id: 1, zipcode: "63109", students: [ { name: "john", school: 102, age: 10 }, { name: "jess", school: 102, age: 11 }, { name: "jeff", school: 108, age: 15 } ] } { _id: 2, zipcode: "63110", students: [ { name: "ajax", school: 100, age: 7 }, { name: "achilles", school: 100, age: 8 }, ] } { _id: 3, zipcode: "63109", students: [ { name: "ajax", school: 100, age: 7 }, { name: "achilles", school: 100, age: 8 }, ] }
查詢zipcode為63109並且students數組中school=102的文檔:
db.schools.find( { zipcode: "63109" },{ students: { $elemMatch: { school: 102 } } } )
返回如下結果:
{ "_id" : 1, "students" : [ { "name" : "john", "school" : 102, "age" : 10 } ] }{ "_id" : 3 }
$slice(projection)
釋義:在查詢中將數組進行切片(類似於分頁)
舉例:
(1)查詢結果中,對於comments數組的元素只顯示前5個: db.posts.find( {}, { comments: { $slice: 5 } } ) (2)查詢結果中,對於comments數組的元素只顯示後5個: db.posts.find( {}, { comments: { $slice: -5 } } ) (3)查詢結果中,對於comments數組的元素跳過(skip)前20個,並只顯示(limit)10個元素(即21-30): db.posts.find( {}, { comments: { $slice: [ 20, 10 ] } } ) (4)同理,跳過後20個,並顯示10個: db.posts.find( {}, { comments: { $slice: [ -20, 10 ] } } )
更新
字段更新
$inc
語法:{ $inc: { : , : , … } }
釋義:將文檔中的某個field對應的value自增/減某個數字amount
舉例:
將_id為1的文檔的age字段在原來的基礎上+1: db.person.update( { _id: 1 }, { $inc: { age: 1} })
$mul
語法:{ $mul: { field: } }
釋義:將文檔中的某個field對於的value做乘法操作
舉例:
將_id為1的文檔的price值乘以1.25並更新: db.products.update( { _id: 1 }, { $mul: { price: 1.25 } })
$rename
語法:{$rename: { : , : , … } }
釋義:重命名文檔中的指定字段的名
舉例:
將_id為1的文檔的nickname字段重命名為alias,cell字段重命名為mobile db.person.update( { _id: 1 }, { $rename: { 'nickname': 'alias', 'cell': 'mobile' } } )
$setOnInsert
語法:
db.collection.update( , { $setOnInsert: { : , … } }, { upsert: true })
釋義:配合upsert操作,在作為insert時可以為新文檔擴展更多的field
舉例:
將_id為1的文檔的item字段更改為apple,並插入新字段defaultQty,值為100 db.products.update( { _id: 1 }, { $set: { item: "apple" }, $setOnInsert: { defaultQty: 100 } }, { upsert: true })
$set
語法:{ $set: { : , … } }
釋義:更新文檔中的某一個字段,而不是全部替換
舉例:
假設現有文檔:
{_id:1,name:"zhangsan",sex:"男"}
如果這樣寫: db.person.update({_id:1},{sex:"女"}); 則更改之後的結果是醬的: {_id:1,sex:"女"} 若只想更改sex字段,可以這樣寫: db.person.update({_id:1},{$set:{sex:"女"}});
$unset
語法:{ $unset: { : “”, … } }
釋義:刪除文檔中的指定字段,若字段不存在則不操作
舉例:
刪除_id為1的文檔的name字段 db.person.update( { _id: 1}, { $unset: { name:"" } })
$min
語法:{ $min: { : , … } }
釋義:將文檔中的某字段與指定值作比較,如果原值小於指定值,則不更新;若大於指定值,則更新
舉例:
假設現有文檔: { _id: 1, highScore: 800, lowScore: 200 } 執行:db.scores.update( { _id: 1 }, { $min: { lowScore: 150 } } ) 執行結果:{ _id: 1, highScore: 800, lowScore: 150 }
$max
語法:{ $max: { : , … } }
釋義:與$min功能相反
$currentDate
語法:{ $currentDate: { : , … } }
釋義:設置指定字段為當前時間
舉例:
db.person.update( { _id: 1 }, { $currentDate: { "lastLogin": { $type: "timestamp" } } })
數組更新
$(update)
語法:{ “.$” : value }
釋義:請參考官網
$addToSet
語法:{ $ addToSet : { < field1 >: < value1 > , … } }
釋義:用於添加一個元素到array中,一般用於update
舉例:
假設現有文檔: { _id: 1, letters: ["a", "b"] } 執行:db.test.update({_id:1},{$addToSet:{letters:"c"}}) 結果:{ "_id" : 1, "letters" : [ "a", "b", "c" ] } 執行:db.test.update({_id:1},{$addToSet:{letters:["d","e"]}}) 結果:{ "_id" : 1, "letters" : [ "a", "b", "c", [ "d", "e" ] ] } 注意,若想讓添加的多個元素分開成單個元素的效果,請參考$each的使用方法
$pop
語法:{ $pop: { : <-1 | 1>, … } }
釋義:刪除數組中的第一個或最後一個元素,-1表示第一個,沒錯,第一個;1表示最後一個!
舉例:
db.test.update({_id:1},{$pop:{letters:-1}});
$pullAll
語法:{ $pullAll: { : [ , … ], … } }
釋義:刪除數組或內嵌文檔字段中所有指定的元素
舉例:
假設現有文檔:{ _id: 1, scores: [ 0, 2, 5, 5, 1, 0 ] } 執行:db.test.update( { _id: 1 }, { $pullAll: { scores: [ 0, 5 ] } } ) 結果:{ "_id" : 1, "scores" : [ 2, 1 ] }
$pull
語法:{ $pull: { : <value|condition>, : <value|condition>, … } }
釋義:刪除滿足條件的元素
舉例:
假設現有文檔:{ _id: 1, votes: [ 3, 5, 6, 7, 7, 8 ] } 執行:db.test.update( { _id: 1 }, { $pull: { votes: { $gte: 6 } } } ) 結果:{ _id: 1, votes: [ 3, 5 ] }
$push
語法:{ $push: { : , … } }
釋義:往數組中追加指定的元素,若文檔中數組不存在,則創建並添加指定元素,自v2.4起,添加了對$.each的支持
舉例:
db.students.update( { _id: 1 }, { $push: { scores: 89 } })
$each
語法:
{ $addToSet: { <field>: { $each: [ <value1>, <value2> ... ] } } } { $push: { <field>: { $each: [ <value1>, <value2> ... ] } } }
釋義:需要搭配\(addToSet或\)push方可使用
$sort
語法:
{ $push: { <field>: { $each: [ <value1>, <value2>, ... ], $sort: <sort specification> } } }
釋義:自v2.4加,配合$push使用,表示給文檔中的指定數組元素排序,1是升序,-1是降序
舉例:
db.students.update( { _id: 1 }, { $push: { quizzes: { $each: [ { id: 3, score: 8 }, { id: 4, score: 7 }, { id: 5, score: 6 } ], $sort: { score: 1 } } } } )
$position
語法:
{ $push: { <field>: { $each: [ <value1>, <value2>, ... ], $position: <num> } } }
釋義:自v2.6加,配合$push使用表示往數組元素中的指定位置插入元素