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

  1. Community server
  2. VS extending
  3. 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

  1. 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
  2. Start a connection

    1. After start the server, you can type mongo in bash to start a connection. Use exit to stop the connection
    2. you can use mongodb compass to start a connection, this is a mongondb management UI
    3. use Datagrip/Dataspell to build a connection

    Notes:

    • The port for local host is always 27017
    • There's no default username and password

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
use <database-name>

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
db.dropDatabase()

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
2
show databases -- list all visible DB
db -- show the current DB

Create and drop colletions

to create a collection in Database:

1
db.createCollection("name",options)

to drop a collection:

1
db.collection_name.drop()

to show collections in current DB

1
show collections

Insert documents

to create one documents:

1
db.C1.insertOne({"name":"A"});

to create many documents:

1
db.C1.insertMany([{"name":"B"},{"name":"C"}])

Note: the input of insertMany() should be a list[]

Update documents

To update a documents

1
2
3
4
5
6
db.C1.updateOne({"name":"B"},{
$set:{
"mobile":"123456"
}
}
)

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
2
3
4
5
6
db.C1.updateMany({"mobile":"123456"},{
$set:{
"mobile":"654321"
}
}
)

Read data

To read(and modify) data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
-- find all documents in the collection
db.C1.find()

--find particular documents
db.C1.find({"name":"A","mobile":"654321"})

-- find the first documents that fits the condition
db.C1.findOne({"mobile":"654321"})

-- find and delete the first documenttaht fits the condition
db.C1.findOneAndDelete({"name":"D"})

-- find and replace the first documenttaht fits the condition
-- the second parameter gives a whole documents(like the format in insert)
db.C1.findOneAndReplace({"name":"A"},{"name":"E","mobile":"23456"})

-- find and update
-- the second parameter gives a the operation to apply on the documents(like the format in update)
db.C1.findOneAndUpdate({"name":"E"},{
$set:{
"mobile":"12345"
}
}
)

-- find and Modify
-- pass a json that tell the command to conduct multiple operaions
db.C1.findAndModify(
{
"query": {"name":"E"},
"update":{$set:{"name":"A"}},
}
)

Delete documents

to delete documents from a collection:

1
2
3
4
-- delete the first documetn fits the condition
db.C1.deleteOne({"mobile":"12345"})
-- delete all documents fit the condition
db.C1.deleteMany({"mobile":"12345"})

Query

The first parameter is called query condition, by passing a json map, you tell the command constraints of fields.

1
db.C1.find({"mobile":"12345","name":"T"})

you can also use the $and operand:

1
2
3
4
5
6
7
db.C1.find(
{
$and:[
{"mobile":"12345"},{"name":"T"}
]
}
)

Other operand in this formats:

  • or
  • nor

to query documents with quantify condition:

1
db.C1.find({"mobile":{$gte:"20000"}})

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
2
3
4
var pipline = [
{$sort:{"name":1}}
]
db.C1.aggregate(pipline)

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
2
3
4
5
var pipline = [
{$sort:{"name":1}},
{$limit:4}
]
db.C1.aggregate(pipline)

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
db.C1.find().limit(3)

showing the first there results

Skip the first 2 results and show the rest:

1
db.C1.find().skip(2)

Sort

to sort results:

1
db.C1.find().sort({"name":-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
2
db.C1.createIndex({"name":1})
db.C1.createIndexes([{"name":1},{"mobile":1}])

Drop index:

1
2
3
4
db.C1.dropIndex({"mobile":1})

-- drop all indexes except _id
db.C1.dropIndexes()

Group by:

Group by operand:

1
2
3
4
5
6
7
8
db.C1.aggregate(
{
$group:{
_id:"$name",
"count":{$sum: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
2
-- dump the current database
mongodump

To restore all databases

1
mongorestore

Transaction

For transation realted content in MongoDB, please refer to this link.


MongoDB Guildbook
http://example.com/2022/02/06/MongoDB-Guildline/
Author
Zhengyuan Yang
Posted on
February 6, 2022
Licensed under