พื้นฐานเชลล์ mongosh
ผู้เรียนจะใช้ mongosh เพื่อสลับฐานข้อมูล แสดงรายการคอลเลกชัน และเรียกใช้คิวรีเอกสารแรกแบบโต้ตอบ
พื้นฐานเชลล์ mongosh เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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 27017Navigating 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
// ordersYour 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 resultsCounting 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();
// 4823Sorting 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.
เรียนรู้ JavaScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 30
- บทเรียน
- 120
คำถามที่พบบ่อย
บทเรียน “พื้นฐานเชลล์ mongosh” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “พื้นฐานเชลล์ mongosh” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “พื้นฐานเชลล์ mongosh”
ผู้เรียนจะใช้ mongosh เพื่อสลับฐานข้อมูล แสดงรายการคอลเลกชัน และเรียกใช้คิวรีเอกสารแรกแบบโต้ตอบ คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “พื้นฐานเชลล์ mongosh” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- เอกสาร BSON คืออะไร
- คอลเลกชันเทียบกับตาราง SQL
- ฐานข้อมูล คอลเลกชัน และเนมสเปซ
- พื้นฐานเชลล์ mongosh