Databases 27 min read

Master MongoDB: From Basics to Advanced Operations

This comprehensive guide introduces MongoDB, explains NoSQL classifications, walks through Windows and Linux installations, demonstrates using the Robo 3T GUI, and covers essential CRUD operations, queries, indexing, sorting, counting, and data deduplication with clear code examples and screenshots.

Ops Development Stories
Ops Development Stories
Ops Development Stories
Master MongoDB: From Basics to Advanced Operations

1. Enter the World of MongoDB

With the rise of big‑data, relational databases (SQL) struggle to keep up, prompting the emergence of NoSQL ("Not only SQL"). In 2009 the distributed document‑oriented database MongoDB sparked a wave of "going NoSQL".

1.1 Classification and Characteristics of NoSQL Databases

Key‑Value Databases – e.g., Redis, Flare, offering extremely high read/write performance for heavy traffic.

Document Databases – e.g., MongoDB, CouchDB, providing flexible schema, easy field addition/removal, and no need for predefined tables.

Column‑Store Databases – e.g., Cassandra, HBase, fast lookups and strong scalability for distributed storage.

Graph Databases – e.g., Neo4j, InfoGrid, using graph algorithms for social networks and recommendation systems.

1.2 What MongoDB Is Good For

MongoDB excels at storing massive amounts of loosely related data. Its storage hierarchy (database → collection → document → field) resembles the relational model but does not require predefined schemas, allowing fields to vary and supporting high‑concurrency writes.

1.3 From Files to MongoDB

While a plain text file or Excel can hold limited rows, datasets exceeding a million rows per day demand a database. MongoDB provides basic storage, logical and mathematical operations, search, bulk updates, and schema‑free documents.

2. MongoDB Quick Start

This section covers MongoDB installation, basic syntax, using the Robo 3T GUI, and Python integration.

2.1 MongoDB vs. SQL Terminology

SQL

MongoDB

Table

Collection

Row

Document

Column

Field

Primary Key

ObjectId

Index

Index

Embedded Table

Embedded Document

Array

Array

2.2 Installing MongoDB

2.2.1 Windows Installation

Download the MSI installer from the official MongoDB download page and click “DOWNLOAD (msi)”.

Run the installer, choose “Custom” installation, and click “Next”.

Set the installation path to

D:\MongoDB\Server\

and finish the setup.

After installation, the binaries reside in

D:\MongoDB\Server\4.2\bin

and the configuration file is

mongod.cfg

.

Log files are stored in

D:\MongoDB\Server\4.2\log

.

2.2.2 Linux Installation (CentOS 7.6 example)

Create a yum repository file:

<code># cd /etc/yum.repos.d
# vim mongodb-org-4.2.repo
[mongodb-org]
name=MongoDB Repository
baseurl=http://mirrors.aliyun.com/mongodb/yum/redhat/7Server/mongodb-org/4.2/x86_64/
gpgcheck=0
enabled=1
</code>

Update packages and install MongoDB:

<code># yum update
# yum -y install mongodb-org
</code>

Verify installation path:

<code># whereis mongod
mongod: /usr/bin/mongod /etc/mongod.conf /usr/share/man/man1/mongod.1
</code>

Edit

/etc/mongod.conf

to bind to all interfaces:

<code># cat /etc/mongod.conf
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true
processManagement:
  fork: true
net:
  port: 27017
  bindIp: 0.0.0.0
</code>

Start, stop, check status, and enable autostart:

<code># systemctl start mongod.service
# systemctl stop mongod.service
# systemctl status mongod.service
# systemctl enable mongod.service
</code>

Disable the default firewall and open port 27017:

<code># systemctl stop firewalld.service
# systemctl disable firewalld.service
# iptables -A INPUT -m state --state NEW -p tcp --dport 27017 -j ACCEPT
</code>

3. Robo 3T – Graphical MongoDB Management

Robo 3T is a free, cross‑platform GUI for MongoDB. Download it from robomongo.org . Installation is straightforward.

Run the installer and accept the user agreement.

Choose the installation path and finish.

To connect, click “Create”, fill a name, and save. Then click “Connect”.

The main interface has three key areas:

Database list (Area A) – select databases and collections.

Data view (Area B) – display documents.

Command editor (Area C) – write and run MongoDB commands.

4. Basic MongoDB Operations

CRUD (Create, Read, Update, Delete) are fundamental. The following examples use the

example_data_1

collection.

4.1 Create Database, Collection, and Insert Data

Create a database named

chapter_1

and a collection.

Insert documents one by one using

insertOne()

.

Insert multiple documents with

insertMany()

.

<code>db.getCollection('example_data_1').insertOne({"name": "王小二", "age": 17, "address": "浙江"})
</code>

4.2 Query Data

Find all documents:

db.getCollection('example_data_1').find()

Find specific value:

db.getCollection('example_data_1').find({'age': 23})

Range query:

db.getCollection('example_data_1').find({'age': {'$gte': 23}})
<code>db.getCollection('example_data_1').find({'age': {'$gte': 23, '$lt': 24}})
</code>

Projection (return specific fields)

<code>db.getCollection('example_data_1').find({}, {'name': 1, 'age': 1, '_id': 0})
</code>

Count, Limit, Sort

<code>db.getCollection('example_data_1').find({'age': {'$gt': 21}}).count()
db.getCollection('example_data_1').find().limit(4)
db.getCollection('example_data_1').find({'age': {'$gt': 21}}).sort({'age': -1})
</code>

4.3 Update Data

Use

updateOne()

for a single document or

updateMany()

for all matching documents.

<code>db.getCollection('example_data_1').updateMany({'name':'王小六'}, {'$set':{'address':'苏州','work':'DBA'}})
</code>

4.4 Delete Data

Delete a single document with

deleteOne()

or multiple with

deleteMany()

.

<code>db.getCollection('example_data_1').deleteMany({'hello': 'world'})
</code>
Tip: In production, prefer a soft‑delete flag (e.g., deleted: 0/1 ) to avoid accidental data loss.

4.5 Distinct (Deduplication)

Retrieve unique values of a field using

distinct()

.

<code>db.getCollection('example_data_1').distinct('age')
db.getCollection('example_data_1').distinct('age', {'age':{'$gte':20}})
</code>
Note: distinct() returns an array of unique values; combining it with other fields requires aggregation pipelines (covered later).
installationMongoDBNoSQLData QueryDatabase TutorialCRUD OperationsRobo 3T
Ops Development Stories
Written by

Ops Development Stories

Maintained by a like‑minded team, covering both operations and development. Topics span Linux ops, DevOps toolchain, Kubernetes containerization, monitoring, log collection, network security, and Python or Go development. Team members: Qiao Ke, wanger, Dong Ge, Su Xin, Hua Zai, Zheng Ge, Teacher Xia.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.