Mongodb tutorial

Time:2021-1-22

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

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:https://www.mongodb.com/downl…

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

D:\software\mongodb\data\db
D:\software\mongodb\log\mongod.log

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

systemLog:
  destination: file
  path: "D:/software/mongodb/log/mongod.log"
  logAppend: true
storage:
  journal:
    enabled: true
  dbPath: "D:/software/mongodb/data/db"
net:
  bindIp: 0.0.0.0
  port: 27017
setParameter:
  enableLocalhostAuthBypass: false

5) . production system services

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

Or specify the configuration directly on the command line

mongod --bind_ip 0.0.0.0 --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

mongo
Link: http://www.runoob.com/mongodb/mongodb-window-install.html
  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
db.createUser(
    {
        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
db.createUser(
    {
        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 0.0.0.0 --install --auth

#Or
mongod --bind_ip 0.0.0.0 --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
mongo
use admin
db.auth("root","123")

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
https://www.mongodb.com/download-center#community

#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:
#   http://docs.mongodb.org/manual/reference/configuration-options/

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

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

# network interfaces
net:
  port: 27017
  bindIp: true


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

6) . background start

mongod -f /etc/mongod.conf &

7) . log in to mongodb

#Login
mongo

#Create database test
use test

#View current database
db

Using Mongo command

#Connect to any database
mongo 127.0.0.1:27017/config

#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('127.0.0.1:27017')
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
db.dropDatabase()

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
db.table1.insert({"a":1})
db.table2.insert({"b":2})

#View table
Show collections or show tables

#Delete
db.user.info . help () # view help
db.user.info.drop()

#Help if you don't understand
db.table.help () examples

Add operation

#Insert single data
user0 = {
    "name": "changhao",
    "age": "23",
    "hobbies": ['music', 'read', 'dancing'],
    "addr": {
        "country": 'China',
        "city": 'BJ',
    }
}
#Mode one
db.table1.insert(user0)
#Mode 2
db.table1.insertOne(user0)

#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
db.table1.find()

#Beautify output
db.table1.find().pretty()

#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
db.table1.find({"_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
db.table1.find({
    "_id":{"$gte":3,"$lte":4},
    "age":{"$gte":40}
})
perhaps
db.table1.find({"$and":[
    {"_ ID ": {" $GTE ": 3," $LTE ": 4}}, a dictionary is a condition
    {"age":{"$gte":40}}
]})

# 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

db.table1.find({
    "name":/^jin.*?(g|n)$/i
})

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
db.table1.find().limit(2)
#Skip the first two of the queried data
db.table1.find().skip(2)
db.table1.sort({"age":-1}).skip(0).limit(2)

Record modification

The syntax format is as follows

db.collection.update(
    <query>,
    <update>,
    {
        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 = obj.name + '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}
db.table1.update({'_id':{"$gt":4}},{"$set":{"age":28}})
db.table1.update({'_id':{"$gt":4}},{"$set":{"age":38}},{"multi":true})

#Modify the embedded document to change the address country of the person whose name is test to Japan
db.table1.update({'name':"test"},{"$set":{"addr.country":"Japan"}})

#Change the two hobbies of the person named test to Piao
db.table1.update({'name':"test"},{"$set":{"hobbies.1":"piao"}})

#Delete test's hobby, $unset
db.table1.update({'name':"test"},{"$unset":{"hobbies":""}})

Increase and decrease

#Increase and decrease $Inc
#1. Increase the age of all by one year
db.table1.update({},
    {
        "$inc":{"age":1}
    },
    {
        "multi":true
    }
)
#2. Age reduction of 5 years for all
db.user.update({},
    {
        "$inc":{"age":-5}
    },
    {
        "multi":true
    }
)

delete

#Delete the first of multiple
db.table1.deleteOne({"age":8})

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

How to use pymongo module

Connect to database

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

print(dblist)
#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"}})
print(res.modified_count)

#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})
print(res.modified_count)

Delete statement

Delete single

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

Delete multiple

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

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