MongoDB Academy · 课时

mongosh Shell 基础

您将使用 mongosh 切换数据库、列出集合,并交互式运行第一个文档查询。

第 4 / 4 课13 个步骤

mongosh Shell 基础 是 CoddyKit 上的免费 MongoDB Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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.

免费开始

用 AI 导师学习 JavaScript — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
30
课程
120

常见问题解答

「mongosh Shell 基础」课时是免费的吗?

是的 — 「mongosh Shell 基础」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 MongoDB Academy 课程的其余内容,请升级到 CoddyKit PRO。 MongoDB Academy 课程共包含 4 节课。

「mongosh Shell 基础」这节课中我会学到什么?

您将使用 mongosh 切换数据库、列出集合,并交互式运行第一个文档查询。 你通过在浏览器中直接运行的动手代码来练习 MongoDB Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 MongoDB Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 MongoDB Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「mongosh Shell 基础」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 MongoDB Academy 课中编写并运行代码吗?

能。每节 MongoDB Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 什么是 BSON 文档
  2. 集合与 SQL 表的比较
  3. 数据库、集合与命名空间
  4. mongosh Shell 基础
← 返回 MongoDB Academy