This cheat sheet has quick reference commands for 这个备忘单有mongosh to get you connected and running CRUD operations as quickly as possible. For more information, see the mongosh documentation.mongosh的快速参考命令,可以让你尽快连接并运行CRUD操作。有关更多信息,请参阅mongosh文档。
Note
This cheat sheet includes common MongoDB commands, but is not comprehensive. See Database Commands and mongosh Methods for full lists.此备忘单包括常见的MongoDB命令,但并不全面。有关完整列表,请参阅数据库命令和mongosh方法。
Connect and Authenticate连接并验证
Connect连接
// Omit password if you want to prompt for it如果要提示输入密码,请省略密码
mongosh --host <host> --port <port> --authenticationDatabase admin -u <user> -p <pwd>
mongosh "mongodb://<user>:<password>@192.168.1.1:27017"
mongosh "mongodb://192.168.1.1:27017"
mongosh "mongodb+srv://cluster-name.abcde.mongodb.net/<dbname>" --apiVersion
1 --username <username> # MongoDB AtlasConnection Information连接信息
db.getMongo() // get connection object获取连接对象
db.getMongo().getDBs() // list databases列表数据库
db.hello()
db.runCommand({ping: 1}) // test connection测试连接
db.listCommands()
db.adminCommand({buildInfo: 1}) // MongoDB build informationMongoDB构建信息Create User and Authenticate创建用户并进行身份验证
use admin
// Create, drop, or authenticating users创建、删除或验证用户
db.createUser({"user": "root", "pwd": passwordPrompt(), "roles": ["root"]})
db.dropUser("root")
db.auth( "user", passwordPrompt() )Common Helpers常见助手
Show Databases显示数据库
show dbs
db // prints the current database打印当前数据库Switch Database交换机数据库
use <database_name>Show Collections显示集合
show collectionsRun JavaScript File运行JavaScript文件
load("myScript.js")CRUD OperationsCRUD操作
Create创建
db.coll.insertOne({name: "Max"})
db.coll.insertMany([{name: "Max"}, {name:"Alex"}]) // ordered bulk insert订购批量插入件
db.coll.insertMany([{name: "Max"}, {name:"Alex"}], {ordered: false}) // unordered bulk insert无序散装插入件
db.coll.insertOne({date: ISODate()})
db.coll.insertOne({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})Read读取
Basic Find Operations基本查找操作
db.coll.findOne() // returns a single document返回单个文档
db.coll.find() // returns a cursor that displays 20 results, use "it" to display more返回一个显示20个结果的游标,使用“it”显示更多结果
db.coll.find().pretty()
db.coll.find({name: "Max", age: 32}) // implicit logical "AND".隐含的逻辑“与”。
db.coll.find({date: ISODate("2020-09-25T13:57:17.180Z")})
db.coll.find({name: "Max", age: 32}).explain("executionStats") // or "queryPlanner" or "allPlansExecution"
db.coll.distinct("name")Count Operations计数操作
// Count计数
db.coll.countDocuments({age: 32}) // $count aggregation alias that returns an accurate count返回准确计数的$count聚合别名
db.coll.estimatedDocumentCount() // uses collection metadata to estimate the document count使用集合元数据来估计文档计数Comparison Operators比较运算符
// Comparison比较
db.coll.find({"year": {$gt: 1970}})
db.coll.find({"year": {$gte: 1970}})
db.coll.find({"year": {$lt: 1970}})
db.coll.find({"year": {$lte: 1970}})
db.coll.find({"year": {$ne: 1970}})
db.coll.find({"year": {$in: [1958, 1959]}})
db.coll.find({"year": {$nin: [1958, 1959]}})Logical Operators逻辑运算符
// Logical逻辑
db.coll.find({name:{$not: {$eq: "Max"}}})
db.coll.find({$or: [{"year" : 1958}, {"year" : 1959}]})
db.coll.find({$nor: [{price: 1.99}, {sale: true}]})
db.coll.find({
$and: [
{$or: [{qty: {$lt :10}}, {qty :{$gt: 50}}]},
{$or: [{sale: true}, {price: {$lt: 5 }}]}
]
})Element Operators元素运算符
// Element元素
db.coll.find({name: {$exists: true}})
db.coll.find({"zipCode": {$type: 2 }})
db.coll.find({"zipCode": {$type: "string"}})Aggregation Pipeline聚合管道
// Aggregation Pipeline聚合管道
db.coll.aggregate([
{$match: {status: "A"}},
{$group: {_id: "$cust_id", total: {$sum: "$amount"}}},
{$sort: {total: -1}}
])Text Search文本搜索
// Create text index for search创建搜索文本索引
db.coll.createIndex({ title: "text", content: "text" })
// Basic text search基本文本搜索
db.coll.find({$text: {$search: "cake"}})
// Text search queries文本搜索查询
db.coll.find({ $text: { $search: "mongodb database" } })
db.coll.find({ $text: { $search: "\"exact phrase\"" } })
db.coll.find({ $text: { $search: "mongodb -database" } }) // exclude "database"排除“数据库”
// Text search with scores带分数的文本搜索
db.coll.find({$text: {$search: "cake"}}, {score: {$meta: "textScore"}}).sort({score: {$meta: "textScore"}})Geospatial Queries地理空间查询
// Create geospatial indexes创建地理空间索引
db.places.createIndex({ location: "2dsphere" }) // For GeoJSON用于GeoJSON
db.places.createIndex({ location: "2d" }) // For legacy coordinates用于传统坐标
// Find locations near a point查找点附近的位置
db.places.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [-73.9857, 40.7484] },
$maxDistance: 1000 // meters
}
}
})
// Find locations within a polygon查找多边形内的位置
db.places.find({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [[
[-74.0059, 40.7128],
[-74.0059, 40.7589],
[-73.9352, 40.7589],
[-73.9352, 40.7128],
[-74.0059, 40.7128]
]]
}
}
}
})Regular Expressions正则表达式
// Regex
db.coll.find({name: /^Max/}) // regex: starts by letter "M":以字母“M”开头
db.coll.find({name: /^Max$/i}) // regex case insensitive正则表达式不区分大小写Array Operations数组操作
// Array数组
db.coll.find({tags: {$all: ["Realm", "Charts"]}})
db.coll.find({field: {$size: 2}}) // can't be indexed, so instead store the size of the array & update it无法索引,因此请存储数组的大小并更新它
db.coll.find({results: {$elemMatch: {product: "xyz", score: {$gte: 8}}}})Projections预测
// Projections
db.coll.find({"x": 1}, {"actors": 1}) // actors + _id
db.coll.find({"x": 1}, {"actors": 1, "_id": 0}) // actors
db.coll.find({"x": 1}, {"actors": 0, "summary": 0}) // all but "actors" and "summary"除了“演员”和“摘要”Sort, Skip, Limit排序、跳过、限制
// Sort, skip, limit排序、跳过、限制
db.coll.find({}).sort({"year": 1, "rating": -1}).skip(10).limit(3)Read Concern读取关注
// Read Concern读取关注
db.coll.find().readConcern("majority")Update更新
Basic Update Operations基本更新操作
db.coll.updateOne({"_id": 1}, {$set: {"year": 2016, name: "Max"}})
db.coll.updateOne({"_id": 1}, {$unset: {"year": 1}})
db.coll.updateOne({"_id": 1}, {$rename: {"year": "date"} })
db.coll.updateOne({"_id": 1}, {$inc: {"year": 5}})
db.coll.updateOne({"_id": 1}, {$mul: {price: NumberDecimal("1.25"), qty: 2}})
db.coll.updateOne({"_id": 1}, {$min: {"imdb": 5}})
db.coll.updateOne({"_id": 1}, {$max: {"imdb": 8}})
db.coll.updateOne({"_id": 1}, {$currentDate: {"lastModified": true}})
db.coll.updateOne({"_id": 1}, {$currentDate: {"lastModified": {$type: "timestamp"}}})Array Update Operations数组更新操作
// Array数组
db.coll.updateOne({"_id": 1}, {$push :{"array": 1}})
db.coll.updateOne({"_id": 1}, {$pull :{"array": 1}})
db.coll.updateOne({"_id": 1}, {$addToSet :{"array": 2}})
db.coll.updateOne({"_id": 1}, {$pop: {"array": 1}}) // last element最后一个元素
db.coll.updateOne({"_id": 1}, {$pop: {"array": -1}}) // first element第一个元素
db.coll.updateOne({"_id": 1}, {$pullAll: {"array" :[3, 4, 5]}})
db.coll.updateOne({"_id": 1}, {$push: {"scores": {$each: [90, 92]}}})
db.coll.updateOne({"_id": 2}, {$push: {"scores": {$each: [40, 60], $sort: 1}}}) // array sorted数组已排序
db.coll.updateOne({"_id": 1, "grades": 80}, {$set: {"grades.$": 82}})
db.coll.updateMany({}, {$inc: {"grades.$[]": 10}})
db.coll.updateMany({}, {$set: {"grades.$[element]": 100}}, {multi: true, arrayFilters: [{"element": {$gte: 100}}]})FindOneAndUpdate
// FindOneAndUpdate
db.coll.findOneAndUpdate({"name": "Max"}, {$inc: {"points": 5}}, {returnNewDocument: true})Upsert
// Upsert
db.coll.updateOne({"_id": 1}, {$set: {item: "apple"}, $setOnInsert: {defaultQty: 100}}, {upsert: true})Replace替换
// Replace
db.coll.replaceOne({"name": "Max"}, {"firstname": "Maxime", "surname": "Beugnet"})Write Concern写关注
// Write concern写关注
db.coll.updateMany({}, {$set: {"x": 1}}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})Batch and Bulk Operations批量和散装操作
// Update many documents efficiently高效地更新许多文档
db.coll.updateMany({status: "pending"}, {$set: {status: "processed"}})
// Delete many documents删除许多文档
db.coll.deleteMany({status: "old"})
// Insert many documents efficiently高效地插入多个文档
db.coll.insertMany([
{name: "user1", status: "active"},
{name: "user2", status: "active"},
{name: "user3", status: "active"}
])
// Bulk operation for mixed insert, update, and delete operations用于混合插入、更新和删除操作的批量操作
// Ordered by default, executed serially. If unordered, MongoDB executes operations in parallel.默认情况下按顺序排列,按顺序执行。如果无序,MongoDB将并行执行操作。
db.coll.bulkWrite([
{ insertOne: { document: { name: "Alice", age: 30 } } },
{ updateOne: { filter: { name: "Bob" }, update: { $set: { age: 25 } } } },
{ deleteOne: { filter: { name: "Charlie" } } }
], ordered: false)Delete删除
db.coll.deleteOne({name: "Max"})
db.coll.deleteMany({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
db.coll.deleteMany({}) // WARNING! Deletes all documents, but not the collection or its index definitions警告!删除所有文档,但不删除集合或其索引定义
db.coll.findOneAndDelete({"name": "Max"})Databases and Collections数据库和集合
Database Information数据库信息
db.getName()
db.getSiblingDB("dbname")
db.stats()Create Collection with Schema Validation使用架构验证创建集合
// Create collection with a $jsonschema使用$jsonschema创建集合
db.createCollection("contacts", {
validator: {$jsonSchema: {
bsonType: "object",
required: ["phone"],
properties: {
phone: {
bsonType: "string",
description: "Required. Must be a string."
},
email: {
bsonType: "string",
pattern: "@mongodb\.com$",
description: "String that matches the regular expression."
},
status: {
enum: [ "Unknown", "Incomplete" ],
description: "Must be one of the preceding enum values."
}
}
}}
})Import or Export Data导入或导出数据
Important
These are MongoDB database tool commands, not mongosh methods. Run them in your system terminal.这些是MongoDB数据库工具命令,而不是mongosh方法。在您的系统终端中运行它们。
// Import JSON data导入JSON数据
mongoimport --db mydb --collection mycoll --file data.json
// Export to JSON导出为JSON
mongoexport --db mydb --collection mycoll --out data.json
// Import CSV data导入CSV数据
mongoimport --db mydb --collection mycoll --type csv --headerline --file data.csv
// Create database dump创建数据库dump
mongodump --db mydb --out backup/
// Restore from dump
mongorestore backup/Drop丢弃
Warning
The following commands delete data permanently. Use them with caution, especially in a production environment.以下命令将永久删除数据。请谨慎使用它们,尤其是在生产环境中。
db.coll.drop() // removes the collection and its index definitions删除集合及其索引定义
db.dropDatabase() // removes the database. USE CAUTION.删除数据库。小心。Other Collection Functions其他集合功能
db.getCollectionNames()
db.getCollectionInfos()
db.printCollectionStats()
db.coll.stats() // collection statistics including size, count, and indexes集合统计信息,包括大小、计数和索引
db.coll.storageSize() // collection data storage size, in bytes集合数据存储大小,以字节为单位
db.coll.totalIndexSize() // total size of all collection indexes所有集合索引的总大小
db.coll.totalSize() // total size of collection data and indexes集合数据和索引的总大小
db.coll.validate({full: true})
db.coll.renameCollection("new_coll", true) // rename collection. WARNING: "true" drops any existing collection with the same name重命名集合。警告:“true”会删除任何同名的现有集合Indexes索引
List Indexes列出索引
db.coll.getIndexes()
db.coll.getIndexKeys()Create Indexes创建索引
Index Types索引类型
// Index Types索引类型
db.coll.createIndex({"name": 1}) // single field index单字段索引
db.coll.createIndex({"name": 1, "date": 1}) // compound index复合索引
db.coll.createIndex({foo: "text", bar: "text"}) // text index
db.coll.createIndex({"$**": "text"}) // wildcard text index通配符文本索引
db.coll.createIndex({"userMetadata.$**": 1}) // wildcard index通配符索引
db.coll.createIndex({"loc": "2d"}) // 2d index
db.coll.createIndex({"loc": "2dsphere"}) // 2dsphere index2维球面索引
db.coll.createIndex({"_id": "hashed"}) // hashed index散列索引Index Options索引选项
// Index Options索引选项
db.coll.createIndex({"lastModifiedDate": 1}, {expireAfterSeconds: 3600}) // TTL index
db.coll.createIndex({"name": 1}, {unique: true})
db.coll.createIndex({"name": 1}, {partialFilterExpression: {age: {$gt: 18}}}) // partial index部分索引
db.coll.createIndex({"name": 1}, {collation: {locale: 'en', strength: 1}}) // case insensitive index with strength 1 or 2强度为1或2的不区分大小写索引
db.coll.createIndex({"name": 1 }, {sparse: true})Drop Indexes丢弃索引
db.coll.dropIndex("name_1")Hide or Unhide Indexes隐藏或取消隐藏索引
db.coll.hideIndex("name_1")
db.coll.unhideIndex("name_1")Transactions and Change Streams事务和变更流
Transactions事务
// Start a session for transactions启动事务会话
session = db.getMongo().startSession()
session.startTransaction()
try {
// Perform multiple operations执行多项操作
session.getDatabase("mydb").mycollection.insertOne({name: "Alice"})
session.getDatabase("mydb").mycollection.updateOne({name: "Bob"}, {$set: {status: "updated"}})
// Commit the transaction提交事务
session.commitTransaction()
} catch (error) {
// Abort the transaction on error发生错误时中止事务
session.abortTransaction()
throw error
} finally {
session.endSession()
}Change Streams更改流
watchCursor = db.coll.watch( [ { $match : {"operationType" : "insert" } } ] )
while (!watchCursor.isExhausted()){
if (watchCursor.hasNext()){
print(tojson(watchCursor.next()));
}
}Server Management and Replication服务器管理和复制
Server Commands服务器命令
db.serverStatus()
db.hostInfo()
db.shutdownServer()
db.fsyncLock() // flush pending operations and lock the server清除挂起的操作并锁定服务器
db.fsyncUnlock() // reduce the lock count on the server减少服务器上的锁数Replica Sets复制集
db.getReplicationInfo()
db.printReplicationInfo()
rs.status()
rs.initiate({"_id": "RS1",
members: [
{ _id: 0, host: "mongodb1.net:27017" },
{ _id: 1, host: "mongodb2.net:27017" },
{ _id: 2, host: "mongodb3.net:27017" }]
rs.add("mongodb4.net:27017")
rs.addArb("mongodb5.net:27017")
rs.remove("mongodb1.net:27017")
rs.conf()
rs.hello()
rs.printReplicationInfo()
rs.printSecondaryReplicationInfo()
rs.reconfig(config)
rs.reconfigForPSASet(memberIndex, config, { options } )
db.getMongo().setReadPref('secondaryPreferred')
rs.stepDown(20, 5) // (stepDownSecs, secondaryCatchUpPeriodSecs)Sharded Clusters分片集群
db.printShardingStatus()
sh.status()
sh.addShard("rs1/mongodb1.example.net:27017")
sh.enableSharding("mydb")
sh.disableSharding("mydb.coll")
sh.shardCollection("mydb.coll", {zipcode: 1})
sh.moveChunk("mydb.coll", { zipcode: "53187" }, "shard0019")
sh.splitChunk("mydb.coll", { "shardKey": value })
sh.splitAt("mydb.coll", {x: 70})
sh.splitFind("mydb.coll", {x: 70})
sh.updateZoneKeyRange("mydb.coll", {state: "NY", zip: MinKey }, { state: "NY", zip: MaxKey }, "NY")
sh.removeRangeFromZone("mydb.coll", {state: "NY", zip: MinKey }, { state: "NY", zip: MaxKey })
sh.addShardToZone("shard0000", "NYC")
sh.removeShardFromZone("shard0000", "NYC")
sh.startAutoMerger()
sh.stopAutoMerger()
sh.enableAutoMerger()
sh.disableAutoMerger()Documents and Fields文件和字段
ObjectIds
// ObjectId
ObjectId() // generates a new ObjectId生成新的ObjectId
ObjectId("507f1f77bcf86cd799439011") // creates ObjectId from string从字符串创建ObjectId
ObjectId().getTimestamp() // returns the timestamp portion返回时间戳部分
ObjectId().toString() // converts to string representation转换为字符串表示
ObjectId().valueOf() // returns the string value返回字符串值Data Types and Type Checking数据类型和类型检查
// BSON data typesBSON数据类型
NumberInt(42) // 32-bit integer
NumberLong(42) // 64-bit integer
NumberDecimal("42.42") // 128-bit decimal128位十进制
// Date operations日期操作
new Date() // current date/time
ISODate() // current date/time in ISO formatISO格式的当前日期/时间
ISODate("2023-01-01") // specific date具体日期
// Binary data二进制数据
BinData(0, "base64encodedstring")
// Regular expressions正则表达式
/<pattern>/<flags>
// Check data types
typeof value
db.coll.find({field: {$type: "string"}})Performance and Optimization性能和优化
// Query performance analysis查询性能分析
db.coll.find({name: "John"}).explain()
db.coll.find({name: "John"}).explain("executionStats")
// Collection statistics收款统计
db.coll.stats()
db.coll.totalIndexSize()
db.coll.storageSize()
// Database profiling and logging数据库分析和日志记录
db.setProfilingLevel(2) // Profile all operations分析所有操作
db.setProfilingLevel(1, 100) // Profile slow operations概述缓慢的操作 (>100ms)
db.setProfilingLevel(0) // Turn off profiling
db.getProfilingStatus()
// View profile data查看配置文件数据
db.system.profile.find().sort({ts: -1}).limit(5)
// Current operations当前操作
db.currentOp()
db.killOp(operationId)
// Server and database stats服务器和数据库统计信息
db.serverStatus()
db.stats()