AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.

MongoDB mongosh 치트 시트

이 치트 시트에는 가능한 한 빨리 연결하고 CRUD 작업을 실행할 수 있도록 mongosh 에 대한 빠른 참조 명령이 포함되어 있습니다.

참고

이 치트 시트에는 일반적인 MongoDB 명령이 포함되어 있지만 포괄적이지 않습니다. 전체 목록은 데이터베이스 명령 및 mongosh 메서드 를 참조하세요.

// Omit password if you want to prompt for itmongosh --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>" --apiVersion1 --username <username> # MongoDB Atlas
db.getMongo() // get connection objectdb.getMongo().getDBs() // list databasesdb.hello()db.runCommand({ping: 1}) // test connectiondb.listCommands()db.adminCommand({buildInfo: 1}) // MongoDB build information
use admin// Create, drop, or authenticating usersdb.createUser({"user": "root", "pwd": passwordPrompt(), "roles": ["root"]})db.dropUser("root")db.auth( "user", passwordPrompt() )
show dbsdb // prints the current database
use <database_name>
show collections
load("myScript.js")
db.coll.insertOne({name: "Max"})db.coll.insertMany([{name: "Max"}, {name:"Alex"}]) // ordered bulk insertdb.coll.insertMany([{name: "Max"}, {name:"Alex"}], {ordered: false}) // unordered bulk insertdb.coll.insertOne({date: ISODate()})db.coll.insertOne({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
db.coll.findOne() // returns a single documentdb.coll.find() // returns a cursor that displays 20 results, use "it" to display moredb.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")
// Countdb.coll.countDocuments({age: 32}) // $count aggregation alias that returns an accurate countdb.coll.estimatedDocumentCount() // uses collection metadata to estimate the document count
// Comparisondb.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]}})
// Logicaldb.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 }}]} ]})
// Elementdb.coll.find({name: {$exists: true}})db.coll.find({"zipCode": {$type: 2 }})db.coll.find({"zipCode": {$type: "string"}})
// Aggregation Pipelinedb.coll.aggregate([ {$match: {status: "A"}}, {$group: {_id: "$cust_id", total: {$sum: "$amount"}}}, {$sort: {total: -1}}])
// Create text index for searchdb.coll.createIndex({ title: "text", content: "text" }) // Basic text searchdb.coll.find({$text: {$search: "cake"}}) // Text search queriesdb.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 scoresdb.coll.find({$text: {$search: "cake"}}, {score: {$meta: "textScore"}}).sort({score: {$meta: "textScore"}})
// Create geospatial indexesdb.places.createIndex({ location: "2dsphere" }) // For GeoJSONdb.places.createIndex({ location: "2d" }) // For legacy coordinates // Find locations near a pointdb.places.find({ location: { $near: { $geometry: { type: "Point", coordinates: [-73.9857, 40.7484] }, $maxDistance: 1000 // meters } }}) // Find locations within a polygondb.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] ]] } } }})
// Regexdb.coll.find({name: /^Max/}) // regex: starts by letter "M"db.coll.find({name: /^Max$/i}) // regex case insensitive
// Arraydb.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 itdb.coll.find({results: {$elemMatch: {product: "xyz", score: {$gte: 8}}}})
// Projectionsdb.coll.find({"x": 1}, {"actors": 1}) // actors + _iddb.coll.find({"x": 1}, {"actors": 1, "_id": 0}) // actorsdb.coll.find({"x": 1}, {"actors": 0, "summary": 0}) // all but "actors" and "summary"
// Sort, skip, limitdb.coll.find({}).sort({"year": 1, "rating": -1}).skip(10).limit(3)
// Read Concerndb.coll.find().readConcern("majority")
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"}}})
// Arraydb.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 elementdb.coll.updateOne({"_id": 1}, {$pop: {"array": -1}}) // first elementdb.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 sorteddb.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}}]})
// FindOneAndUpdatedb.coll.findOneAndUpdate({"name": "Max"}, {$inc: {"points": 5}}, {returnNewDocument: true})
// Upsertdb.coll.updateOne({"_id": 1}, {$set: {item: "apple"}, $setOnInsert: {defaultQty: 100}}, {upsert: true})
// Replacedb.coll.replaceOne({"name": "Max"}, {"firstname": "Maxime", "surname": "Beugnet"})
// Write concerndb.coll.updateMany({}, {$set: {"x": 1}}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
// Update many documents efficientlydb.coll.updateMany({status: "pending"}, {$set: {status: "processed"}}) // Delete many documentsdb.coll.deleteMany({status: "old"}) // Insert many documents efficientlydb.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.db.coll.bulkWrite([ { insertOne: { document: { name: "Alice", age: 30 } } }, { updateOne: { filter: { name: "Bob" }, update: { $set: { age: 25 } } } }, { deleteOne: { filter: { name: "Charlie" } } }], ordered: false)
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 definitionsdb.coll.findOneAndDelete({"name": "Max"})
db.getName()db.getSiblingDB("dbname")db.stats()
// Create collection with a $jsonschemadb.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." } } }}})

중요

이는 mongosh 메서드가 아닌 MongoDB database 도구 명령입니다. 시스템 터미널에서 실행합니다.

// Import JSON datamongoimport --db mydb --collection mycoll --file data.json // Export to JSONmongoexport --db mydb --collection mycoll --out data.json // Import CSV datamongoimport --db mydb --collection mycoll --type csv --headerline --file data.csv // Create database dumpmongodump --db mydb --out backup/ // Restore from dumpmongorestore backup/

경고

다음 명령은 데이터를 영구적으로 삭제 . 특히 프로덕션 환경에서는 주의해서 사용하세요.

db.coll.drop() // removes the collection and its index definitionsdb.dropDatabase() // removes the database. USE CAUTION.
db.getCollectionNames()db.getCollectionInfos()db.printCollectionStats() db.coll.stats() // collection statistics including size, count, and indexesdb.coll.storageSize() // collection data storage size, in bytesdb.coll.totalIndexSize() // total size of all collection indexesdb.coll.totalSize() // total size of collection data and indexesdb.coll.validate({full: true})db.coll.renameCollection("new_coll", true) // rename collection. WARNING: "true" drops any existing collection with the same name
db.coll.getIndexes()db.coll.getIndexKeys()
// Index Typesdb.coll.createIndex({"name": 1}) // single field indexdb.coll.createIndex({"name": 1, "date": 1}) // compound indexdb.coll.createIndex({foo: "text", bar: "text"}) // text indexdb.coll.createIndex({"$**": "text"}) // wildcard text indexdb.coll.createIndex({"userMetadata.$**": 1}) // wildcard indexdb.coll.createIndex({"loc": "2d"}) // 2d indexdb.coll.createIndex({"loc": "2dsphere"}) // 2dsphere indexdb.coll.createIndex({"_id": "hashed"}) // hashed index
// Index Optionsdb.coll.createIndex({"lastModifiedDate": 1}, {expireAfterSeconds: 3600}) // TTL indexdb.coll.createIndex({"name": 1}, {unique: true})db.coll.createIndex({"name": 1}, {partialFilterExpression: {age: {$gt: 18}}}) // partial indexdb.coll.createIndex({"name": 1}, {collation: {locale: 'en', strength: 1}}) // case insensitive index with strength 1 or 2db.coll.createIndex({"name": 1 }, {sparse: true})
db.coll.dropIndex("name_1")
db.coll.hideIndex("name_1")db.coll.unhideIndex("name_1")
// Start a session for transactionssession = 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()}
watchCursor = db.coll.watch( [ { $match : {"operationType" : "insert" } } ] ) while (!watchCursor.isExhausted()){ if (watchCursor.hasNext()){ print(tojson(watchCursor.next())); }}
db.serverStatus()db.hostInfo()db.shutdownServer() db.fsyncLock() // flush pending operations and lock the serverdb.fsyncUnlock() // reduce the lock count on the server
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)
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()
// ObjectIdObjectId() // generates a new ObjectIdObjectId("507f1f77bcf86cd799439011") // creates ObjectId from stringObjectId().getTimestamp() // returns the timestamp portionObjectId().toString() // converts to string representationObjectId().valueOf() // returns the string value
// BSON data typesNumberInt(42) // 32-bit integerNumberLong(42) // 64-bit integerNumberDecimal("42.42") // 128-bit decimal // Date operationsnew Date() // current date/timeISODate() // current date/time in ISO formatISODate("2023-01-01") // specific date // Binary dataBinData(0, "base64encodedstring") // Regular expressions/<pattern>/<flags> // Check data typestypeof valuedb.coll.find({field: {$type: "string"}})
// Query performance analysisdb.coll.find({name: "John"}).explain()db.coll.find({name: "John"}).explain("executionStats") // Collection statisticsdb.coll.stats()db.coll.totalIndexSize()db.coll.storageSize() // Database profiling and loggingdb.setProfilingLevel(2) // Profile all operationsdb.setProfilingLevel(1, 100) // Profile slow operations (>100ms)db.setProfilingLevel(0) // Turn off profilingdb.getProfilingStatus() // View profile datadb.system.profile.find().sort({ts: -1}).limit(5) // Current operationsdb.currentOp()db.killOp(operationId) // Server and database statsdb.serverStatus()db.stats()