MongoDB (mongosh) 명령어 치트시트
mongosh 빠른 참조: 연결, CRUD, 쿼리 연산자, aggregation 파이프라인, 인덱스, replica set, 사용자, dump/restore — 가장 흔한 셸 패턴과 실전 예시까지 정리했습니다.
명령어 30개
연결 & 메타
mongosh "<uri>"표준 연결 URI 로 MongoDB 에 연결합니다.
--quiet; --eval 'cmd'; --file script.js; --apiVersion 1/2
mongosh "mongodb://app:[email protected]:27017/app_production?authSource=admin"show dbs / use <db> / show collectionsDB 목록; DB 전환; 현재 DB 의 컬렉션 목록.
show dbs | use app | show collectionsdb.serverStatus() / db.stats()서버 정보: 연결, opcounters, 복제 상태; db stats: 크기와 컬렉션.
.pretty() 로 보기 좋게; .verbose(); .json; --eval 결과
db.serverStatus().connections && db.stats().dataSizeCRUD: Read
db.<coll>.find()컬렉션을 쿼리; .pretty() .limit() .skip() .sort() 를 체인해 결과를 다룹니다.
.projection({name:1, email:1, _id:0}); .sort({createdAt:-1}); .limit(20); .skip(20); .count(); .allowDiskUse()
db.orders.find({status:'paid', amount:{$gte:10}}).sort({createdAt:-1}).limit(20).pretty()db.<coll>.findOne({...}) / db.<coll>.countDocuments({...})단일 문서를 읽거나, 필터에 매치되는 문서 개수를 셉니다.
findOne 필터 유무; estimatedDocumentCount 는 O(1)
db.users.findOne({email:'[email protected]'}, {pwd:0, _id:0}) && db.orders.countDocuments({status:'paid'})CRUD: Create
db.<coll>.insertOne({...}) / insertMany([...])문서 한 개/여러 개 삽입; 옵션: ordered:false 는 일부 실패해도 유효한 문서는 모두 기록합니다.
db.logs.insertMany([{k:'api', t:new Date()}, {k:'worker', t:new Date()}], {ordered:false})CRUD: Update
db.<coll>.updateOne(filter, update, opts)문서 하나를 업데이트. $set $inc $push $pull $addToSet $rename $unset 같은 연산자 사용.
upsert:true; arrayFilters:[] 중첩 배열용; returnDocument:'after' (findOneAndUpdate)
db.users.updateOne({email:'[email protected]'}, {$inc:{loginCount:1}, $set:{lastSeen:new Date()}}, {upsert:true})db.<coll>.updateMany(filter, update) / findOneAndUpdate여러 문서를 업데이트(쓰기는 bulk); findOneAndUpdate 는 업데이트 전/후 문서를 원자적으로 반환.
db.orders.updateMany({status:'pending', createdAt:{$lt:new Date(Date.now()-864e5)}}, {$set:{status:'cancelled'}})CRUD: Replace
db.<coll>.replaceOne(filter, replacement)_id 를 제외한 문서 전체를 교체(replacement 에 _id 허용 안 함).
db.users.replaceOne({email:'[email protected]'}, {name:'Alice', email:'[email protected]', role:'admin', tags:['vip']})CRUD: Delete
db.<coll>.deleteOne / deleteMany(filter)필터에 매치되는 문서를 제거. deleteMany({}) 는 모든 것을 삭제(주의해서 사용).
db.sessions.deleteMany({lastSeen:{$lt:new Date(Date.now()-7*864e5)}}) && db.orders.deleteOne({_id:ObjectId('...')})쿼리 연산자
Comparison: $eq / $ne / $gt / $gte / $lt / $lte / $in / $nin표준 비교 연산자; $in 은 값 목록과 매치됩니다.
db.orders.find({amount:{$gte:10,$lt:100}, status:{$in:['paid','shipped']}})Logical: $and / $or / $not / $nor조건 결합; $not 은 regex/메타데이터만, regex 는 명시적 regex 필요.
db.products.find({$or:[{sale:true,price:{$lt:50}},{tags:'vip'}]})$exists / $type / $regex / $expr / $mod필드 단위 조건: 존재, BSON 타입, regex 매치, 집계 비교($expr), $mod.
db.users.find({email:{$exists:true, $regex:'@example.com$', $options:'i'}})db.<coll>.distinct(field, filter)필드의 고유 값을 가져옵니다(필터 옵션).
db.orders.distinct('userId', {status:'paid'}).lengthAggregation
.aggregate([...])스테이지 파이프라인 구성: $match → $group → $project → $sort → $limit → $lookup → $unwind → $facet.
.explain('executionStats'); allowDiskUse:true; collation 문서
db.orders.aggregate([ { $match:{status:'paid'} }, { $group:{_id:'$userId', gmv:{$sum:'$amount'}, n:{$sum:1}} }, { $sort:{gmv:-1} }, { $limit:50} ])$lookup / $graphLookup컬렉션 간 조인($lookup)과 재귀 트리 탐색($graphLookup).
db.orders.aggregate([{$lookup:{from:'users', localField:'userId', foreignField:'_id', as:'user'}}, {$unwind:'$user'}, {$project:{total:1, 'user.name':1}}])$bucket / $bucketAuto / $sample / $sortByCount유용한 집계 연산자: 버킷팅, 샘플링, top-N 카운팅.
db.events.aggregate([{$sample:{size:100}}, {$group:{_id:'$kind', n:{$sum:1}}}])인덱스
db.<coll>.createIndex(spec, opts)단일/복합/지오/텍스트/TTL 인덱스를 만듭니다.
{unique:true, partialFilterExpression, sparse, expireAfterSeconds, weights, name}
db.users.createIndex({email:1}, {unique:true}) && db.events.createIndex({ts:1}, {expireAfterSeconds:7*86400}) && db.shops.createIndex({loc:'2dsphere'})db.<coll>.getIndexes() / dropIndex / dropIndexes인덱스 목록; 한 개/전체 삭제(운영에서는 함부로 호출하지 말 것).
db.users.getIndexes().forEach(i=>print(i.name, JSON.stringify(i.key)))db.<coll>.explain('executionStats').find(filter)승리한 플랜과 실제 실행 통계 조회. COLLSCAN, IXSCAN, FETCH, sort stage 를 살펴보세요.
executionStats / queryPlanner / allPlansExecution; verbosity
db.orders.find({userId:42,createdAt:{$gte:new Date('2026-01-01')}}).sort({createdAt:-1}).explain('executionStats').queryPlanner.winningPlandb.<coll>.hint({...})플래너가 특정 인덱스를 사용하도록 강제 — 잘못된 플랜, 회귀 디버깅용.
db.users.find({email:'[email protected]'}).hint({email:1}).explain()유지 보수
db.runCommand({...}) / db.adminCommand / db.commandMongoDB 명령을 직접 실행. 셸 헬퍼에 없는 연산을 위한 탈출구.
db.runCommand({listCollections:1, name:'app'}) && db.adminCommand({listDatabases:1}).databases.lengthdb.revokeRolesFromUser / grantRolesToUser역할 관리(admin DB 에서 실행).
use admin; db.createUser({user:'audit',pwd:'...',roles:[{role:'readAnyDatabase',db:'admin'}]})Replica Set
rs.initiate() / rs.status()단일 노드 replica set 부트스트랩; 헬스 표시.
rs.initiate({_id:'rs0',members:[{_id:0,host:'m1:27017'}]}); rs.status().myState
rs.initiate({_id:'rs0',members:[{_id:0,host:'m1:27017'},{_id:1,host:'m2:27017'},{_id:2,host:'m3:27017'}]})rs.add / rs.remove / rs.stepDown멤버 추가/제거; 페일오버 테스트를 위한 선출 강제.
rs.add('m4:27017'); rs.remove('m3:27017'); rs.stepDown(60)
rs.add('m4.internal:27017') && rs.stepDown(60) && sh.status() on the next memberSharded Cluster
sh.status() / sh.enableSharding클러스터 토폴로지 조회 / 데이터베이스에 sharding 활성화.
use admin; sh.enableSharding('analytics'); sh.shardCollection('analytics.events', {userId:1, ts:1})백업 & 마이그레이션
mongodump / mongorestore논리 백업/복원. --uri, --db, --archive 로 스트리밍; --gzip 으로 압축.
--gzip; --archive=file.archive; --oplog point-in-time; --nsInclude/Exclude
mongodump --uri="mongodb://user:pw@m1:27017/?authSource=admin" --gzip --archive=/backup/app-2026-07-23.archive && mongorestore --gzip --archive=/backup/app.archive --nsInclude='app.*' --dropmongoexport / mongoimportJSON/CSV 로 export/import. Mongo 와 다른 시스템 사이에 파이프하는 엔진 역할.
--type=json|csv; --fields=a,b,c; --headerline; -q filter; --jsonArray (단일 최상위 배열)
mongoexport --uri="..." -d app -c orders --type=json -q '{"status":"paid"}' --out=orders.json && mongoimport --drop --jsonArray orders.json -d copy -c ordersmongotop / mongostat실시간 모니터링: 지난 1초 동안 각 컬렉션이 읽기/쓰기에 사용한 시간과 통계.
간격(초); --host
mongostat --host=m1.internal --authdb=admin --username=ops -i 5db.shutdownServer()admin DB 에서 실행해 mongod 를 깔끔히 종료 — rm/poweroff 후 복구에도 유용.
use admin; db.shutdownServer({force:true}? No; clean shutdown waits for oplog replication)
use admin; db.shutdownServer()치트시트 버전 1.0.0
MongoDB 6.0+ / mongosh 1.6+ 대응