MongoDB Guildbook
MongoDB
About MongoDB
MongoDB is a open- source NoSQL database stroing data in json like documents with schema.
mongoDB do not have concepts like join.
mongoDB provides APIs for most programing language
Three ways to access MongoDB
- Community server
- VS extending
- MongoDB Altas
Concepts in MondoDB:
Document: a set of K-V pairs. Every document has a unique value via key "_id". Documents have dynamic schema, documents in same collection can have different schema. They. Can hold data of any types allowed by mongodb.
Collection: a group of mongodb documents, similar to "tables in other database. Unlike tables, collections does nothave any schema definition, and it cannnot be join. Usually, documents with in a collection belonging to a particular subject.
Database: A database is a container of collections of data
Comparison between RDBMS and MongoDB
RDBMS | |||
---|---|---|---|
Tables | stand for entity | Collections | A set of documents representing one object |
rows | stand for an actual record | Documents | a json objects |
columns | stand for attributes | Fields | The first level of the schema |
Start with MongoDB
Build a sever(for Mac)
1
mongod --config /opt/homebrew/etc/mongod.conf
This create a temp mongo server. If you close the session by ctrl+c, he connecttion would be terminated
Or you can use the command
1
brew services start mongodb/brew/mongodb-community
This create a back-support mongoDB server, you can still access to it after you close the terminal, to stop the back-support:
1
brew services stop mongodb/brew/mongodb-community
Start a connection
- After start the server, you can type
mongo
in bash to start a connection. Useexit
to stop the connection - you can use mongodb compass to start a connection, this is a mongondb management UI
- use Datagrip/Dataspell to build a connection
Notes:
- The port for local host is always 27017
- There's no default username and password
- After start the server, you can type
Data types in MongoDB
Allowed data dytes in mongoDB include:
BSON
A mongoDB data type, it's binary encoded json that can processed faster, it support some types(data, timestamp,object id) that are not supported by json
JSON
Integer
Boolean
Double
Arrays
Objects
Used to store embedded documents. If a documents A contains a K-V pair {"file":B}, where B is another document, the type of B in A's schema is Object
Null
Date
Timestemp
Object ID
ObjectIds are small, likely unique, fast to generate, and ordered. It's a usually used as a PK of a document. ObjectId values are 12 bytes in length, consisting of a 4-bytes timestamp value representiong the ObjectId's creation, a 5-bytes random value, a 3-byte incrementing value
Code
Like javascript code
Create and Drop Database
you can create databse by:
1 |
|
It would select the DB, if not exists, it create the DB
Notes: The created databse will not be visible untill you insert any data into it
To drop the database:
1 |
|
where db
refer to the currently used database.
Before you drop the DB, makesure you select the DB first.
Some other commands related to create and drop
1 |
|
Create and drop colletions
to create a collection in Database:
1 |
|
to drop a collection:
1 |
|
to show collections in current DB
1 |
|
Insert documents
to create one documents:
1 |
|
to create many documents:
1 |
|
Note: the input of insertMany() should be a list[]
Update documents
To update a documents
1 |
|
Where:
- the first parameter eplicts the documents to update
- the second parameter explicts the operation to conduct
Notes:This command only applies to the first document that meet the search condition(the first pararmeter)
to update many documents:
1 |
|
Read data
To read(and modify) data:
1 |
|
Delete documents
to delete documents from a collection:
1 |
|
Query
The first parameter is called query condition, by passing a json map, you tell the command constraints of fields.
1 |
|
you can also use the $and operand:
1 |
|
Other operand in this formats:
- or
- nor
to query documents with quantify condition:
1 |
|
Other operand in this formats:
- lte: less than ot equal
- gt: greater than
- lt: less than
- eq: equal
- neq: not equal
Select specific fields
to select specific fields:
1 |
|
Notes:
- the first parameter explicts the query condition
- the second parameter explicts the fields you want or do not want(Projection)
- You can not mix inclusion and exclusion in the second parameter like {"name":0,"mobile":1}
- **The only field that can be mixed is "_id"** of documents. {"name":1,"_id":0}
Projection
Projection is a mechanism allowing you to select specific fieds, like slice of an array.
Aggregation
To perform aggregation on collections:
1 |
|
where pip line is list of operations,
- $count
- $group
- $limit
- $lookup
- $match
- $merge
- $sort
- project
- unwind
- unset
Limit and skip
Limit the results returned by:
1 |
|
showing the first there results
Skip the first 2 results and show the rest:
1 |
|
Sort
to sort results:
1 |
|
where the json map in sort() specify the sorting depending on which fields. 1 for ascending and -1 for descending. If you pass multiple fields, it sort the next fields in the groups of previous fields.
Create and Drop index
Create indexes:
1 |
|
Drop index:
1 |
|
Group by:
Group by operand:
1 |
|
Where:
- _id is an essential arguments, it explain group by which field
- put a $ before the field to group by, it's necessary
- if you want to group by multiple levels, use _id:["$name","$mobile"]
- the "count" is an alias defined by user
- {$sum:1} = count(*)
- {$sum:"$field"} = sum(field)
- other operans includes: $avg, $min, $max
- $push: push all values of the given field in the group into one array
- $addToSet: same as $push, but return a unique set
- $first, $last: return the first/last value
- if _id:null, then return all documents in one group
Back up & Restore
to back up all databases
1 |
|
To restore all databases
1 |
|
Transaction
For transation realted content in MongoDB, please refer to this link.