0Pricing
MongoDB Academy · 강의

mongosh 셸 핵심

mongosh를 사용하여 데이터베이스를 전환하고 컬렉션을 나열하며 첫 문서 쿼리를 대화형으로 실행합니다.

mongosh 셸 핵심은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What Is mongosh?

mongosh is MongoDB's official shell, built on Node.js — so you can use modern JavaScript right inside it. It's the standard way to connect from the command line.

# Install mongosh on macOS
brew install mongosh

# Connect to a local MongoDB instance
mongosh

# Connect to an Atlas cluster
mongosh 'mongodb+srv://user:pass@cluster0.abc.mongodb.net/myapp'

# Connect with explicit host and port
mongosh --host localhost --port 27017

Navigating Databases and Collections

A few commands help you get around: show dbs lists databases, use switches one, and show collections lists what's inside. The db variable is always your current database.

// Navigate in mongosh
show dbs
// admin   0.000GB
// myapp   0.008GB

use myapp
// switched to db myapp

db
// myapp

show collections
// users
// orders

Your First Insert

Adding your first document is one line: insertOne. It returns the new _id, and a quick findOne confirms it saved. The code walks through both steps.

// Insert one document
db.users.insertOne({
  name: 'Alice',
  email: 'alice@example.com',
  age: 28,
  createdAt: new Date()
});
// { acknowledged: true, insertedId: ObjectId('64a2f3b1...') }

// Verify it was stored
db.users.findOne();
// { _id: ObjectId('64a2f3b1...'), name: 'Alice', ... }

Basic find() Queries

find returns all matching documents; pass a filter to narrow it, or use findOne for exactly one. An empty filter returns everything. The code shows a few.

// Find all documents
db.users.find({});

// Find with an equality filter
db.users.find({ name: 'Alice' });

// findOne by _id
db.users.findOne({ _id: ObjectId('64a2f3b1...') });

// Find with multiple conditions (implicit AND)
db.users.find({ age: 28, active: true });

// Type 'it' in shell to get next 20 results

Counting and Limiting Results

A few helpers control how much you get back: countDocuments, plus limit and skip on a query. Together, limit and skip are the basis of pagination. The code shows them.

// Count active users
db.users.countDocuments({ active: true });
// 842

// Get first 5 users
db.users.find({}).limit(5);

// Skip first 10, get next 5 (page 3 of 5-per-page)
db.users.find({}).skip(10).limit(5);

// Fast approximate total
db.users.estimatedDocumentCount();
// 4823

Sorting Query Results

Chain sort to order results — 1 for ascending, -1 for descending. You can even sort by several fields at once as tiebreakers. The code shows a few sorts.

// Sort by age descending (oldest first)
db.users.find({}).sort({ age: -1 });

// Sort by last name then first name
db.users.find({}).sort({ lastName: 1, firstName: 1 });

// Most recently created first
db.users.find({}).sort({ createdAt: -1 }).limit(10);

// Combined: find active users, sort by age, limit to 5
db.users.find({ active: true }).sort({ age: 1 }).limit(5);

Projections: Selecting Fields

A projection picks which fields come back — 1 to include, 0 to exclude. It trims bandwidth and memory when you don't need every field. The code shows examples.

// Include only name and email (exclude everything else)
db.users.find({}, { name: 1, email: 1 });
// { _id: ObjectId('...'), name: 'Alice', email: 'alice@...' }

// Exclude _id too
db.users.find({}, { name: 1, email: 1, _id: 0 });
// { name: 'Alice', email: 'alice@...' }

// Exclude sensitive fields
db.users.find({}, { passwordHash: 0, ssn: 0 });

Pretty Printing and Shell Helpers

mongosh pretty-prints results for you automatically. Handy helpers include toArray, forEach, distinct, and explain to peek at how a query runs. The code shows them.

// Get all distinct cities from user addresses
db.users.distinct('address.city');
// ['Chicago', 'London', 'Tokyo', ...]

// Iterate with forEach
db.users.find({ active: true }).forEach(user => {
  print(user.name + ' - ' + user.email);
});

// Check if query uses an index
db.users.find({ email: 'alice@test.com' }).explain('executionStats');

Quick Update and Delete Commands

You'll cover full CRUD later, but the essentials are updateOne, deleteOne, and deleteMany. Always use $set in updates, or you'll replace the whole document!

// Update a specific field (CORRECT: use $set)
db.users.updateOne(
  { email: 'alice@example.com' },
  { $set: { age: 29, updatedAt: new Date() } }
);

// Delete one document
db.users.deleteOne({ email: 'alice@example.com' });

// WARNING: This REPLACES the entire document (no $set):
// db.users.updateOne({ email: '...' }, { age: 29 });
// Now the document has ONLY { _id, age: 29 } !!!

Shell Variables and Scripting

Since mongosh is real JavaScript, you can use variables, loops, and scripts to automate tasks — far more powerful than a plain SQL CLI. The code shows a loop.

// Variable-driven query
const targetCity = 'Chicago';
const users = db.users.find({ 'address.city': targetCity }).toArray();
print('Users in ' + targetCity + ': ' + users.length);

// For loop to seed test data
for (let i = 1; i <= 10; i++) {
  db.products.insertOne({ name: 'Product ' + i, price: i * 10 });
}

// Run from CLI without entering the shell:
// mongosh mydb --eval "db.users.countDocuments({})"

Connecting to Atlas From the Shell

To reach Atlas, grab the connection string from its UI — it uses mongodb+srv, which finds your cluster via DNS. Store it in an env var, not your shell history.

# Store URI in environment variable (never hard-code credentials)
export MONGODB_URI='mongodb+srv://alice:s3cr3t@cluster0.abc.mongodb.net'

# Connect from shell
mongosh $MONGODB_URI

# Switch to your app database
use myapp

# Verify connection
db.runCommand({ ping: 1 })
# { ok: 1 }

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

You learned mongosh is a JavaScript shell, that projections pick fields, and that you chain sort, limit, and skip to shape results. Next: inserting documents.

자주 묻는 질문

“mongosh 셸 핵심” 강의는 무료인가요?

네 — “mongosh 셸 핵심” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“mongosh 셸 핵심”에서 뭘 배우나요?

mongosh를 사용하여 데이터베이스를 전환하고 컬렉션을 나열하며 첫 문서 쿼리를 대화형으로 실행합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“mongosh 셸 핵심” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. BSON 문서란 무엇인가요?
  2. 컬렉션과 SQL 테이블 비교
  3. 데이터베이스, 컬렉션, 네임스페이스
  4. mongosh 셸 핵심
← MongoDB Academy(으)로 돌아가기