Learning MongoDB

Learning MongoDB

MongoDB is a type of NoSQL database suitable for storing large-scale data.

MongoDB is a document based database, the data is stored in a JSON-like document format.

MongoDB uses Collections to organize documents, and each document is composed of key-value pairs.

Concepts

  1. Database: A container for storing data, similar to a database in relational database.

  2. Collection: A collection in database, similar to a table in relational database.

  3. Document: A data record in a collection, similar to a row in relational database, stored in BSON format.

MongoDB stores data as a document, with a data structure consisting of key-value pairs. The document is similar to a JSON object, and field values can contain other documents, arrays, and document arrays.

mapping:

SQL Concept MongoDB Concept Remark
database database database
table collection databse table/collection
row document data record
column field data field
index index index
table joins MongoDB not supported
primary key primary key MongoDB will set _id to primary key

Installation

bash
1
2
3
4
5
# install community edition
brew install mongodb-community

# start on startup
brew services start mongodb-community

MongoDB Shell

MongoDB Shell is a interactive interface provided by official, allowing users to interact with the MongoDB database, execute commands, and operate the database.

The MongoDB Shell is based on JavaScript and allows users to operate the MongoDB database directly from the command line or within scripts using the JavaScript language.

bash
1
2
3
4
5
6
7
8
9
10
# start mongo shell

# in older versions
mongo

# in the new version
mongosh

# connect to a remote mongodb server
mongosh --host <hostname>:<port>

Basic Operations

mongosh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# show current database
db;

# show database list
show dbs;

# switch to the specified database
use <db_name>;

# execute query operation
db.<collection_name>.find();

# insert a document
db.<collection_name>.insertOne({...});

# update a document
db.<collection_name>.updateOne({...}, {...});

# delete a document
db.<collection_name>.deleteOne({...});

# exit shell
quit()
exit

MongoDB Tools

  1. MongoDB Compass: A free GUI tool.
  2. Navicat: A paid GUI tool.
  3. Studio 3T: A paid GUI tool, with a good CRUD operations experience.

References

  1. https://www.mongodb.com/docs/manual/introduction/
  2. https://www.runoob.com/mongodb/mongodb-tutorial.html

评论