mongodb语法
参考文档:https://docs.mongodb.com/manual/reference/
BSON Types
BSON Type有2种标识符,整形和字符串
| 类型 | 数值 | 字符串 | 说明 | |
|---|---|---|---|---|
| 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” |
可以使用***$type***操作符使用这些类型。
BSON特定类型
ObjectId
近似唯一,快速生成,已排序的类型,12byte**。**
String
UTF-8格式,
Timestamps
Date
64位整形,从1970.01.01开始的毫秒数。
查询和投影操作符
| Name | 意义 |
|---|---|
| 比较操作符 | |
| $eq | 相等 |
| $gt | 大于 |
| $gte | 大于等于 |
| $in | 包含在集合中 |
| $lt | 小于 |
| $lte | 小于等于 |
| $ne | 不等于 |
| $nin | 不在集合中 |
| 逻辑操作符 | |
| $and | AND |
| $not | NOT |
| $nor | 同时满足2个条件的,则为false |
| $or | OR |
| 元素操作符 | |
| $exists | 字段存在 |
| $type | 字段类型为指定类型 |
| 表达式计算 | |
| $expr | |
| $jsonSchema | |
| $mod | |
| $regex | 正则表达式 |
| $text | |
| $where | |
| 地理空间 | |
| $geoIntersects | |
| $geoWithin | |
| $near | |
| $nearSphere | |
| 数组操作符 | |
| $all | 包含所有指定的元素 |
| $elemMatch | 存在元素匹配所有指定条件 |
| $size | 指定数组大小 |
| 二进制操作 | |
| $bitsAllClear | |
| $bitsAllSet | |
| $bitsAnyClear | |
| $bitsAnySet | |
| 注释 | |
| $comment | |
| 投影 | |
| $ | 投影第一个数组元素 |
| $elemMatch | 投影第一个匹配条件的元素 |
| $meta | |
| $slice |
Update操作
| 操作符 | 说明 | 语法 |
|---|---|---|
| 字段操作 | ||
| $currentDate | 设置字段值为当前日期 | |
| $inc | 字段值加上指定值 | |
| $min | 仅当指定值小于字段值时更新 | |
| $max | 仅当指定值大于字段值时更新 | |
| $mul | 字段值乘以指定值 | |
| $rename | 字段重命名 | |
| $set | 设置字段值为指定值 | |
| $setOnInsert | 当文档新增时设置值。 | |
| $unset | 移除字段值 | |
| 数组操作 | ||
| $ | 代指匹配查询条件的第一个元素 | |
| $[] | 代指匹配查询条件的所有元素 | |
| $[] | 代指匹配arrayFilters的所有元素 | |
| $addToSet | 如果元素不存在则加入数组 | |
| $pop | 移除第一或最后的元素 | |
| $pull | 移除匹配条件的所有元素 | |
| $push | 增加一个元素到数组 | |
| $pullAll | 移除匹配一个集合的所有元素 | |
| 修饰 | ||
| $each | 修饰 p u s h , push, push,addToSet,循环数组中的每个元素当做一个对象,而不是整个数组作为一个对象 | |
| $position | 修饰$push,指定插入位置 | |
| $slice | 修饰$push,限制修改数组的大小 | |
| $sort | 修饰$push,排序数组 | |
| 位运算 | ||
| $bit | Performs bitwise AND, OR, and XOR updates of integer values. |
聚合管道阶段
MongoDB的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。
表达式:处理输入文档并输出。表达式是无状态的,只能用于计算当前聚合管道的文档,不能处理其它的文档。
集合聚合
db.collection.aggregate()
除了$out, $merge, and $geoNear,所有阶段都可以出现多次。
| Stage | Description | 示例 |
|---|---|---|
| $addFields | 增加新字段到文档中,类似 p r o j e c t 。 project。 project。set is an alias for $addFields. | |
| $bucket | ||
| $bucketAuto | ||
| $collStats | ||
| $count | 文档总数 | |
| $facet | ||
| $geoNear | 输出接近某一地理位置的有序文档 | |
| $graphLookup | ||
| $group | 分组 | { $group: { _id: null, count: { $sum: 1 } } } |
| $indexStats | ||
| $limit | 取n条记录 | { $limit : 5 } |
| $listSessions | ||
| $lookup | 从另外一个文档引入字段 | |
| $match | 用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。 | { $match : { score : { $gt : 70, $lte : 90 } } } |
| $merge | 把结果输出到指定collection | |
| $out | 把结果输出到指定collection | { $out: “” } |
| $planCacheStats | ||
| $project | 修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。 | $project : { title : 1,author : 1 ,} |
| $redact | ||
| $replaceRoot | 用replacementDocument代替当前文档 | { $replaceWith: } |
| $replaceWith | 同$replaceRoot | |
| $sample | 随机取样 | { $sample: { size: 3 } } |
| $set | 增加字段 | { $set: { : , … } } |
| $skip | 跳过n条记录 | { $skip : 5 } |
| $sort | 排序 | { $sort : { age : -1, posts: 1 } } |
| $sortByCount | 分组count,再倒序 | { s o r t B y C o u n t : " sortByCount: " sortByCount:"tags" } 等价于: { $group: { _id: , count: { $sum: 1 } } }, { $sort: { count: -1 } } |
| $unset | 排除字段 | { $unset: [ “”, “”, … ] } |
| $unwind | 把数组属性平铺,1条记录会平铺成n条记录 | {$unwind: { path: , includeArrayIndex: , //保存元素索引的新字段 preserveNullAndEmptyArrays: //true:path为null, missing,empty array,输出文档。false:不输出 } } |
数据库聚合
db.aggregate( [ { <stage> }, ... ] )
since 3.6
聚合管道操作(标量函数)
| Name | Description | 示例 |
|---|---|---|
| 数学计算 | ||
| $abs | 求绝对值 | |
| $add | 加法 | |
| $ceil | 大于等于指定值的最小整数 | |
| $divide | 除法 | |
| $exp | 指数 | |
| $floor | 小于等于指定值的最大整数 | |
| $ln | 自然对数 | |
| $log | 对数 | |
| $log10 | 10为底对数 | |
| $mod | 求模 | |
| $multiply | 乘法 | |
| $pow | 求幂 | |
| $round | round | |
| $sqrt | 求二次根 | |
| $subtract | 减法 | |
| $trunc | 截断 | |
| 数组操作 | ||
| $arrayElemAt | 求index | |
| $arrayToObject | 数组转document | |
| $concatArrays | 连接数组 | |
| $filter | 过滤 | |
| $in | 在集合中 | |
| $indexOfArray | 第一个匹配的index | |
| $isArray | 是否数组 | |
| $map | map | |
| $objectToArray | 对象转数组 | |
| $range | ||
| $reduce | ||
| $reverseArray | ||
| $size | 数组大小 | |
| $slice | 数组切片 | |
| $zip | 合并2个数组 | |
| 逻辑表达式 | ||
| $and | and | |
| $not | not | |
| $or | or | |
| 比较操作符 | ||
| $cmp | *比较**2**个操作数* | |
| $eq | 相等 | |
| $gt | 大于 | |
| $gte | 大于等于 | |
| $lt | 小于 | |
| $lte | 小于等于指定值的最大整数 | |
| $ne | 不等 | |
| 条件操作符 | ||
| Name | Description | |
| $cond | ||
| $ifNull | ||
| $switch | ||
| 日期操作 | ||
| $dateFromParts | ||
| $dateFromString | ||
| $dateToParts | ||
| $dateToString | ||
| $dayOfMonth | ||
| $dayOfWeek | ||
| $dayOfYear | ||
| $hour | ||
| $isoDayOfWeek | ||
| $isoWeek | ||
| $isoWeekYear | ||
| $millisecond | ||
| $minute | ||
| $month | ||
| $second | ||
| $toDate | ||
| $week | ||
| $year | ||
| $add | ||
| $subtract | ||
| 字面表达式 | ||
| $literal | ||
| 对象表达式 | ||
| $mergeObjects | ||
| $objectToArray | ||
| 集合操作 | ||
| $allElementsTrue | ||
| $anyElementTrue | ||
| $setDifference | ||
| $setEquals | ||
| $setIntersection | ||
| $setIsSubset | ||
| $setUnion | ||
| 字符串操作 | ||
| $concat | ||
| $dateFromString | ||
| $dateToString | ||
| $indexOfBytes | ||
| $indexOfCP | ||
| $ltrim | ||
| $regexFind | ||
| $regexFindAll | ||
| $regexMatch | ||
| $rtrim | ||
| $split | ||
| $strLenBytes | ||
| $strLenCP | ||
| $strcasecmp | ||
| $substr | ||
| $substrBytes | ||
| $substrCP | ||
| $toLower | ||
| $toString | ||
| $trim | ||
| $toUpper | ||
| 文本操作 | ||
| $meta | ||
| 三角 函数 | ||
| $sin | ||
| $cos | ||
| $tan | ||
| $asin | ||
| $acos | ||
| $atan | ||
| $atan2 | ||
| $asinh | ||
| $acosh | ||
| $atanh | ||
| $degreesToRadians | ||
| $radiansToDegrees | ||
| 类型操作 | ||
| $convert | Converts a value to a specified type.(since4.0) | |
| $toBool | Converts value to a boolean.(since4.0) | |
| $toDate | Converts value to a Date.(since4.0) | |
| $toDecimal | Converts value to a Decimal128.(since4.0) | |
| $toDouble | Converts value to a double.(since4.0) | |
| $toInt | Converts value to an integer.(since4.0) | |
| $toLong | Converts value to a long.(since4.0) | |
| $toObjectId | Converts value to an ObjectId.(since4.0) | |
| $toString | Converts value to a string.(since4.0) | |
| $type | Return the BSON data type of the field. | |
| 聚合操作 | ||
| $addToSet | ||
| $avg | ||
| $first | ||
| $last | ||
| $max | ||
| $mergeObjects | ||
| $min | ||
| $push | ||
| $stdDevPop | ||
| $stdDevSamp | ||
| $sum | ||
| Accumulators (in Other Stages) | ||
| $avg | ||
| $max | ||
| $min | ||
| $stdDevPop | ||
| $stdDevSamp | ||
| $sum | ||
| 变量操作 | ||
| $let |
命令
启动shell
启动shell,连接mongo
mongo
mongo --port 28015
mongo "mongodb://mongodb0.example.com:28015"
mongo --host mongodb0.example.com:28015
mongo --host mongodb0.example.com --port 28015
mongo --help
#连接副本
mongo "mongodb://mongodb0.example.com.local:27017,mongodb1.example.com.local:27017,mongodb2.example.com.local:27017/?replicaSet=replA"
shell命令
db相关
#显示正在使用db
db
#选择db
use <database>
#显示所有db
show dbs
show databases
show users
show roles
show logs
#格式化结果
.pretty()
#退出
quit()
#显示db相关命令
db.help()
collection相关
#显示所有collection
show collections
#
db.collection.help()
CRUD操作
插入
db.collection.insertOne({})
db.collection.insertMany([])
db.collection.insert() //insert one or many
db.collection.save()
db.collection.bulkWrite([ <operation 1>, <operation 2>, ... ],{writeConcern : <document>,ordered : <boolean>}
)
修改
db.collection.updateOne(<filter>, <update>, <options>)
db.collection.updateMany(<filter>, <update>, <options>)
db.collection.replaceOne(<filter>, <update>, <options>)
db.collection.findOneAndReplace().
db.collection.findOneAndUpdate().
db.collection.findAndModify().
删除
db.collection.deleteMany()
db.collection.deleteOne()
db.collection.findOneAndDelete()
db.collection.findAndModify()
查询
db.collection.find()db.collection.findOne
索引
db.collection.createIndex( <key and index type specification>, <options> )
db.collection.getIndexes()
db.collection.dropIndex()
db.collection.dropIndexes()
参考:https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/#db.collection.createIndex
附录
参考:
shell:https://docs.mongodb.com/manual/mongo/
CRUD:https://docs.mongodb.com/manual/crud/
methods:https://docs.mongodb.com/manual/reference/method/