mongodb 常用操作符

最近常用mongodb数据库,但是很多操作符不清楚或不知道,所有抽空根据手册整理下,以便于以后查阅(基于3.4版本)

1.查询和投影操作符

1.1比较操作符

$eq 
匹配字段值等于指定值的文档

{ <field>: { $eq: <value> } }
  • 1

$gt 
匹配字段值大于指定值的文档

{ <field>: { $gt: <value> } }
  • 1

$gte 
匹配字段值大于等于指定值的文档

{ <field>: { $gte: <value> } }
  • 1

$lt 
匹配字段值小于指定值的文档

{ <field>: { $gte: <value> } }
  • 1

$lte 
匹配字段值小于等于指定值的文档

{ <field>: { $lte: <value> } }
  • 1

$ne 
匹配字段值不等于指定值的文档,包括没有这个字段的文档

{ <field>: { $ne: <value> } }
  • 1

$in 
匹配字段值等于指定数组中的任何值

{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }
  • 1

字段值为数组类型时,数组中至少有一个元素在指定数组中

{ _id: 1, item: "abc", qty: 10, tags: [ "school", "clothing" ], sale: false }
db.inventory.update(
                     { tags: { $in: ["appliances", "school"] } },
                     { $set: { sale:true } }
                   )
sale值被成功改为true                   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

$nin 
字段值不在指定数组或者不存在

{ field: { $nin: [ <value1>, <value2> ... <valueN> ]} }
  • 1

字段值为数组类型时,数组中没有一个元素与指定数组中元素相等

1.2逻辑操作符

$or 
文档至少满足其中的一个表达式

{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }
  • 1

$and

{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }
  • 1

$not 
字段值不匹配表达式或者字段值不存在

{ field: { $not: { <operator-expression> } } }
  • 1

$nor 
字段值不匹配所有的表达式的文档,包括那些不包含这些字段的文档

{ $nor: [ { <expression1> }, { <expression2> }, ...  { <expressionN> } ] }
  • 1

1.3元素操作符

$exists 
<boolean> 等于true时,字段存在,包括字段值为null的文档 
<boolean> 等于false时,字段不存在

 { field: { $exists: <boolean> } }
  • 1

$type 
匹配字段值为指定数据类型的文档

{ field: { $type: <BSON type number> | <String alias> } }
  • 1
TypeNumberAliasNotes
Double 1 “double”  
String 2 “string”  
Object 3 “object”  
Array 4 “array”  
Binary data 5 “binData”  
Undefined 6 “undefined” Deprecated.
ObjectId 7 “objectId”  
Boolean 8 “bool”  
Date 9 “date”  
Null 10 “null”  
Regular Expression 11 “regex”  
DBPointer 12 “dbPointer” Deprecated.
JavaScript 13 “javascript”  
Symbol 14 “symbol” Deprecated.
JavaScript (with scope) 15 “javascriptWithScope”  
32-bit integer 16 “int”  
Timestamp 17 “timestamp”  
64-bit integer 18 “long”  
Decimal128 19 “decimal” New in version 3.4.
Min key -1 “minKey”  
Max key 127 “maxKey”  

举例如下:

db.addressBook.insertMany(
   [
      { "_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) }
   ]
)

db.addressBook.find( { "zipCode" : { $type : 2 } } );
db.addressBook.find( { "zipCode" : { $type : "string" } } );
查询结果为:
{ "_id" : 1, "address" : "2030 Martian Way", "zipCode" : "90698345" }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

1.4评估操作符

$mod 
匹配字段值被除有指定的余数的文档

{ field: { $mod: [ divisor(除数), remainder(余数) ] } }
  • 1
{ "_id" : 1, "item" : "abc123", "qty" : 0 }
{ "_id" : 2, "item" : "xyz123", "qty" : 5 }
{ "_id" : 3, "item" : "ijk123", "qty" : 12 }

db.inventory.find( { qty: { $mod: [ 4, 0 ] } } )
查询结果为:
{ "_id" : 1, "item" : "abc123", "qty" : 0 }
{ "_id" : 3, "item" : "ijk123", "qty" : 12 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

$regex 
正则表达式可以匹配到的文档

{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
  • 1
  • 2
  • 3
OptionDescriptionSyntax Restrictions
i 对大小写不敏感  
m 多行匹配  
x 忽略空格  
s 使点号可以匹配换行符  

$text 
针对创建了全文索引的字段进行文本搜索

{
  $text:
    {
      $search: <string>,
      $language: <string>,
      $caseSensitive: <boolean>,
      $diacriticSensitive: <boolean>
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

$where 
可以通过js表达式或js函数来查询文档

1.5数组操作符

$all 
字段值是包含所有指定元素的数组的文档

{ <field>: { $all: [ <value1> , <value2> ... ] } }
  • 1

举例如下:

{
   _id: ObjectId("5234cc89687ea597eabee675"),
   code: "xyz",
   tags: [ "school", "book", "bag", "headphone", "appliance" ],
}

{
   _id: ObjectId("5234cc8a687ea597eabee676"),
   code: "abc",
   tags: [ "appliance", "school", "book" ],
}

{
   _id: ObjectId("5234ccb7687ea597eabee677"),
   code: "efg",
   tags: [ "school", "book" ],
}

{
   _id: ObjectId("52350353b2eff1353b349de9"),
   code: "ijk",
   tags: [ "electronics", "school" ],
}

db.inventory.find( { tags: { $all: [ "appliance", "school", "book" ] } } )

查询结果:
{
   _id: ObjectId("5234cc89687ea597eabee675"),
   code: "xyz",
   tags: [ "school", "book", "bag", "headphone", "appliance" ],
}

{
   _id: ObjectId("5234cc8a687ea597eabee676"),
   code: "abc",
   tags: [ "appliance", "school", "book" ],
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

$elemMatch 
数组字段至少一个元素满足所有指定查询条件的文档

{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }
  • 1

$size 
匹配数组字段元素个数等于指定数量的文档

db.collection.find( { field: { $size: 2 } } );
  • 1

1.6投影操作符

$ (projection) 
限定查询结果中指定数组字段返回满足条件的第一个元素 
举例如下:

文档集合
{ "_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 ] }

查询语句
db.students.find( { semester: 1, grades: { $gte: 85 } },
                  { "grades.$": 1 } )

查询结果
{ "_id" : 1, "grades" : [ 87 ] }
{ "_id" : 2, "grades" : [ 90 ] }
{ "_id" : 3, "grades" : [ 85 ] }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

$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 },
           ]
}
{
 _id: 4,
 zipcode: "63109",
 students: [
              { name: "barney", school: 102, age: 7 },
              { name: "ruth", school: 102, age: 16 },
           ]
}

查询语句:
db.schools.find( { zipcode: "63109" },
                 { students: { $elemMatch: { school: 102 } } } )

查询结果:
{ "_id" : 1, "students" : [ { "name" : "john", "school" : 102, "age" : 10 } ] }
{ "_id" : 3 }
{ "_id" : 4, "students" : [ { "name" : "barney", "school" : 102, "age" : 7 } ] }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

$slice (projection) 
控制指定数组字段返回元素个数

db.collection.find( { field: value }, { array: {$slice: count } } );
  • 1

2.更新操作符

2.1字段更新

$inc 
给一个字段增加指定值

{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
  • 1

$mul

{ $mul: { field: <number> } }
  • 1

$rename

{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }
  • 1

$setOnInsert 
upsert为true时,有插入文档操作时插入指定字段值

db.collection.update(
   <query>,
   { $setOnInsert: { <field1>: <value1>, ... } },
   { upsert: true }
)
  • 1
  • 2
  • 3
  • 4
  • 5

$set

{ $set: { <field1>: <value1>, ... } }
  • 1

$unset 
删除指定字段

{ $unset: { <field1>: "", ... } }
  • 1

$min 
指定值小于当前值则更新为指定值

{ $min: { <field1>: <value1>, ... } }
  • 1

$max 
指定值大于当前值则更新为指定值

{ $max: { <field1>: <value1>, ... } }
  • 1

$currentDate 
设置字段值为当前日期 
指定值为true设置为当前日期, 或者{ $type: “timestamp” }或{ $type: “date” }的形式”timestamp”和”date”必须是小写的

{ $currentDate: { <field1>: <typeSpecification1>, ... } }
  • 1

2.2数组更新


更新指定数组的第一个元素

 { "<array>.$" : value } 
  • 1
  • 2

$addToSet 
数组字段增加一个值

{ $addToSet: { <field1>: <value1>, ... } }
  • 1

$pop 
删除数组字段中的第一个或最后一个元素

{ $pop: { <field>: <-1 | 1>, ... } }
  • 1

$pullAll 
删除数组字段中所有指定值,如果指定值为数组,则删除匹配数组内的元素

{ $pullAll: { <field1>: [ <value1>, <value2> ... ], ... } }
  • 1

$pull 
符合条件的值将被删除

{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }
  • 1

$pushAll 
向数组中追加多个指定值

{ $pushAll: { <field>: [ <value1>, <value2>, ... ] } }
  • 1

$push 
向数组中追加值

{ $push: { <field1>: <value1>, ... } }
  • 1

$each 
用于 $addToSet添加多个值到数组中

{ $addToSet: { <field>: { $each: [ <value1>, <value2> ... ] } } }
  • 1

追加多个值到数组中

{ $push: { <field>: { $each: [ <value1>, <value2> ... ] } } }
  • 1

$slice 
限定$push操作时数组元素的个数 
必须和$each一起使用

{
  $push: {
     <field>: {
       $each: [ <value1>, <value2>, ... ],
       $slice: <num>
     }
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

$sort 
与$each一起使用

{
  $push: {
     <field>: {
       $each: [ <value1>, <value2>, ... ],
       $sort: <sort specification>
     }
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

$position 
与$each一起使用 
<num>从0开始的索引值

{
  $push: {
    <field>: {
       $each: [ <value1>, <value2>, ... ],
       $position: <num>
    }
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3.聚合管道操作符

$project 
管道中字段的增加、删除和重命名

{ $project: { <specification(s)> } }
  • 1

$match

{ $match: { <query> } }
  • 1

$limit

{ $limit: <positive integer> }
  • 1

$skip

{ $skip: <positive integer> }
  • 1

$unwind 
文档按照数组字段进行拆分 
举例如下:

文档:
{ "_id" : 1, "item" : "ABC1", sizes: [ "S", "M", "L"] }

管道语句:
db.inventory.aggregate( [ { $unwind : "$sizes" } ] )

结果:
{ "_id" : 1, "item" : "ABC1", "sizes" : "S" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "M" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "L" }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

$group

{ $group: { _id: <expression>, <field1>: { <accumulator1> : <expression1> }, ... } }
  • 1

举例如下

文档集合:
{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 }
{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 }
{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 }
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 }
{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }

分组:
db.books.aggregate(
   [
     { $group : { _id : "$author", books: { $push: "$title" } } }
   ]
)

结果:
{ "_id" : "Homer", "books" : [ "The Odyssey", "Iliad" ] }
{ "_id" : "Dante", "books" : [ "The Banquet", "Divine Comedy", "Eclogues" ] }

分组:
db.books.aggregate(
   [
     { $group : { _id : "$author", books: { $push: "$$ROOT" } } }
   ]
)

结果:
{
  "_id" : "Homer",
  "books" :
     [
       { "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 },
       { "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }
     ]
}

{
  "_id" : "Dante",
  "books" :
     [
       { "_id" : 8751, "title" : "The Banquet", "author" : "Dante", "copies" : 2 },
       { "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 },
       { "_id" : 8645, "title" : "Eclogues", "author" : "Dante", "copies" : 2 }
     ]
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

$sort

{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }
  • 1

$lookup 
两个集合之间的关联

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

$count

{ $count: <string> }

posted on 2018-08-29 12:19  ExplorerMan  阅读(1918)  评论(0编辑  收藏  举报

导航