Mongodb tutorial


By Chang Gao
Email < Wu_ chang_ [email protected] >

Knowledge points

  • Mongodb installation
  • Using Mongo command
  • Mongo basic operation
  • How to use pymongo module

Mongodb installation

Windows installation mode

1) . download the installation package

Mongodb provides pre compiled binary packages for 32-bit and 64 bit systems. You can download and install them from mongodb official website. Download address of mongodb pre compiled binary package is:…

2) . installation

Specify the installation path. I will install it in D:: (software) mongodb. Add D:: (software) mongodb to the environment variable.

3) . new directory and folder


4) . create a new configuration file\ mongod.cfg

  destination: file
  path: "D:/software/mongodb/log/mongod.log"
  logAppend: true
    enabled: true
  dbPath: "D:/software/mongodb/data/db"
  port: 27017
  enableLocalhostAuthBypass: false

5) . production system services

mongod --config "D:\software\mongodb\mongod.cfg" --bind_ip --install

Or specify the configuration directly on the command line

mongod --bind_ip --port 27017 --logpath D:\software\mongodb\log\mongod.log --logappend --dbpath    D:\software\mongodb\data\db --serviceName "mongodb" --serviceDisplayName "mongodb" --install

6) . start mongodb service

net start MongoDB
net stop MongoDB

7) . log in to mongodb

  When there is no account password login, the default is administrator login. Because it was not specified when the system service was just installed
  --Auth (if not specified, there is no authorization), (equivalent to MySQL skipping authorization table startup)

8) . create users with permissions

use admin
        User: "root", # this root can be written at will
        pwd: "123",
        Roles: [{role: "root", DB: "admin"}] # permissions, where role is root and administrator,

use test
        user: "test",
        pwd: "123",
        roles: [
        {role: "readwrite", DB: "test"}, # has read-write permission for test library, and has read-write permission for operating own library
        {role: "read", db: "db1"}
        ]# for the read permission of db1 library, other libraries have read permission

9) . restart the database

mongod --remove
mongod --config "D:\software\mongodb\mongod.cfg" --bind_ip --install --auth

mongod --bind_ip --port 27017 --logpath D:\software\mongodb\log\mongod.log --logappend --dbpath
D:\software\mongodb\data\db --serviceName "MongoDB" --serviceDisplayName "MongoDB" --install --auth

10) . log in again

#Mode one
mongo --port 27017 -u "root" -p "123" --authenticationDatabase "admin"
#Method 2: after login, use db.auth (account, password) login
use admin

How to install Linux

1) . installation dependency

yum install -y libcurl openssl

2) . download mongodb source code installation or Yum Manager installation

#Mongodb source code download address

#Install using yum
yum install -y mongodb

3) . create database directory

#Create a directory and set user permissions
mkdir -p /var/lib/mongo
mkdir -p /var/log/mongodb
chown `whoami` /var/lib/mongo
chown `whoami` /var/log/mongodb

4) . configure Mongo service parameters to allow all IP access

mongod --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongod.log --bind_ip_all --fork

5) . or modify the configuration file / etc/ mongod.conf

# mongod.conf
# for documentation of all options, see:

# Where and how to store data.
  dbPath: /var/lib/mongo
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
  port: 27017
  bindIp: true

# how the process runs
  timeZoneInfo: /usr/share/zoneinfo

6) . background start

mongod -f /etc/mongod.conf &

7) . log in to mongodb


#Create database test
use test

#View current database

Using Mongo command

#Connect to any database

#Do not connect to any database
mongo --nodb

#After startup, run the new Mongo (host name) command when necessary to connect to the desired mongod
conn = new Mongo('')
db = conn.getDB('admin')

#Display all the databases in the current database
Show databases or show DBS

#Use a database and create it if it does not exist
use database

#Delete database

Mongo basic operation

Explanation of related terms and corresponding relationship of SQL terms in mongodb

SQL terms Mongodb terms Explanation / explanation
database database database
table collection Database tables / collections
row document Database record line / document
column field Data field / field
index index Indexes
table joins Table join, mongodbb does not support
primary key primary key Primary key, mongodb will automatically_ The ID field sets the primary key

Some database names are reserved and can directly access these special databases

  • admin:From a permissions point of view, this is the “root” database. If a user is added to the database, the user automatically inherits the permissions of all databases. Some specific server-side commands can only be run from this database, such as listing all databases or shutting down the server.
  • local:This data will never be copied and can be used to store any collection limited to a single local server
  • config:When Mongo is used for sharding settings, the config database is used internally to save sharding related information.

Addition, deletion and modification of set (table)

use test
#Add table content

#View table
Show collections or show tables

#Delete . help () # view help

#Help if you don't understand () examples

Add operation

#Insert single data
user0 = {
    "name": "changhao",
    "age": "23",
    "hobbies": ['music', 'read', 'dancing'],
    "addr": {
        "country": 'China',
        "city": 'BJ',
#Mode one
#Mode 2

#Insert multiple data
user1 = {
    "_id": 1,
    "name": "changhao1",
    "age": "23",
    "hobbies": ['music', 'read', 'dancing'],
    "addr": {
        "country": 'China',
        "city": 'BJ',

user2 = {
    "_id": 2,
    "name": "changhao2",
    "age": "23",
    "hobbies": ['music', 'read', 'dancing'],
    "addr": {
        "country": 'China',
        "city": 'BJ',
#Mode one
db.table1.insertMany(user1, user2)
#Mode 2
db.table1.insertMany([user1, user2])

Find operation

#View all records

#Beautify output

#Find all that match the criteria
db.table1.find({"name": "changhao"})

#Find the first one that meets the criteria
db.table1.findOne({"name": "changhao"})

Conditional search comparison operation

# id = 1

# id != 1
db.table1.find({"_id": {"$ne": 1}})

# id < 2
db.table1.find({"_id": {"$lt": 1}})

# id > 1
db.table1.find({"_id": {"$gt": 1}})

# id >= 1
db.table1.find({"_id": {"$gte": 1}})

# id <= 2
db.table1.find({"_id": {"$lte": 1}})

Conditional search – logical operation

#Logical operations: $and, $or, $not
# id >=3 and id <= 4
db.table1.find({"_id": {"$gte":3, "$lte":4}})

# id >=3 and id <=4 and age >=40
    {"_ ID ": {" $GTE ": 3," $LTE ": 4}}, a dictionary is a condition

# id >=0 and id <=1 or id >=4 or name = "changhao"
db.table1.find({"$or": [
{"_id": {"$lte": 1, "$gte": 0}},
{"_id": {"$gte": 4}},
{"name": "changhao"}

#ID% 2 = 1 odd
db.table1.find({"_id": {"$mod": [2, 1]}})

#Even, negative
db.table1.find({"_id": {"$mod": [2, 1]}})

Regular matching


Sort, skip, intercept

#Sort, according to age sort, 1 positive order, 1 reverse order
db.table1.find().sort("age": 1)
#Select two pieces of data
#Skip the first two of the queried data

Record modification

The syntax format is as follows

        upsert: <boolean>,
        multi: <boolean>,
        writeConcern: <document>

Parameter Description:

  • Query: equivalent to where condition
  • Update: the object of update and some Update Operators (such as inc… etc., equivalent to the operator after set)
  • Upert: optional. The default value is false. If there is no update record, it will not be updated or inserted. If it is set to true, it will be inserted.
  • Multi: optional. The default value is false, which means only the first record found will be updated. If true is set, it means all the records found will be updated.
  • Writeconcern: optional, the level of exception thrown.

Actual combat statement

#1. Coverage
db.table1.update({'age': 20}, {"name": "changhao"})

#2. This simple update completely replaces the match
var obj = db.table1.findOne({"_id": 2})
obj.username = + 'test'
obj.age = 23
db.table1.update({"_id": 1}, obj)

set up

#Set $set
Usually only a part of the document needs to be updated. You can use atomic update modifiers to specify that certain fields in a document are updated.
Update modifier is a special key used to specify complex update operations, such as modify, add and delete

# set  name="changhao" where id = 2
db.table1.update({'_id': 2}, {"$set": {"name": "changhao", "age": 23}, {"upsert":true})

#If the match is not successful, add a new {"upsert": true}
db.table1.update({'_id':2},{"$set":{"name":"changhao", "age":23}},{"upsert":true})

#By default, only the first item successfully matched is changed, {"multi": change multiple items}

#Modify the embedded document to change the address country of the person whose name is test to Japan

#Change the two hobbies of the person named test to Piao

#Delete test's hobby, $unset

Increase and decrease

#Increase and decrease $Inc
#1. Increase the age of all by one year
#2. Age reduction of 5 years for all


#Delete the first of multiple

#Delete all countries as China
db.table1.deleteMany({"": "China"})

How to use pymongo module

Connect to database

import pymongo
client = pymongo.MongoClient("", 27017)
#Displays all databases on the server
dblist = client.database_names()

#Print information: ['admin ',' config ',' local ',' test ']

#Connect to the database and get the library. If the library name exists, use it. If it does not exist, create it
db = client['test']

Add database content

#Add single
mydict = {"name": "changhao001", "age": 23}
res = db.table1.insert_one(mydict)
print( res.inserted_ ID) # returns the objectid object

#Add more
mylist = [{"name": "changhao002", "age": 23}, {"name": "changhao003", "age": 23}]
res = db.table1.insert_many(mylist)
print( res.inserted_ IDS) # returns the list of objectid objects

Query statement

Query a statement

#Query a piece of data
res1 = db.table1.find_one({'name': 'changhao1'})
Print (res1. Items()) ා view the matching data content

Query all or more data in the collection

#Query all or more data in the collection
res2 =  db.stu.find ({}) # query all records
res3 = db.stu.find({"age": 23})

Advanced query

#Older than 20
myquery = {"age": {"$gt": 20}}
res = db.table1.find(myquery)

Regular expression query

#Read the data with the first letter "C" in the name field
myquery = {"name": {"$regex": "^c"}}
res = db.table1.find(myquery)
#Traverse the matching data
for x in res: print(x)

Sort, skip and intercept query results

#Sorting, skipping, and intercepting query results
sort_ res = list( db.table1 .find().sort("age",  pymongo.DESCENDING ))# query all results and sort them in descending order according to age
skip_ res = list( db.table1 . find (). Skip (2)) # query all results and filter out the first two
limit_ res = list( db.table1 . find (). Limit (2)) # query all results and intercept the first two

#Pagination effect
pagination_res = list(db.table1.find().sort("age", pymongo.DESCENDING).limit(2).skip(2))

Modify statement

#Query the direct update setting value
res = db.table1.update_one({'_id': 1}, {"$set": {"name": "changhao_update"}})

#Query the record and add the value in the dictionary
res = db.table1.find_one({"name": "changhao_update"})
res['age'] = 20
#Update values to records
res = db.table1.update_one({"name": "changhao_update"}, {"$set": res})

Delete statement

Delete single

#Delete one of the results
res = db.table1.delete_one({"name": "changhao_update"})

Delete multiple

#Delete multiple, regular matching data
query = {"name": {"$regex": "^c"}}
res = db.table1.delete_many(query)

#Delete all
del_res = db.table1.delete_many({})