MongoDB使用

基本概念:

 库:

MYSQL:
  database

MongDB:
  database

 表:

MYSQL:
  tables

MongDB:
  collections

命令行操作:

制作系统服务:

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

启动服务

net start MongoDB

打开mongoDB客户端

mongo

查看所有数据库

# MySQL
show databases;

# mongoDB
show dbs 
show databases

查看当前数据库

db

创建数据库

# MySQL:
create database db1;

# MongDB:
use user:有则切换,没有就直接创建

添加账户

MongoDB:
# 创建管理员用户:
# 在admin下创建管理员权限
use admin db.createUser({ user: "root", pwd: "123", roles: [   {role: "root", db: "admin"}     ] }) # 创建普通用户 use user db.createUser({ user: "chuck", pwd: "123", roles: [   {role: "readWrite", db: "user",}     ] })

#在test库下创建用户,该用户对test有读写权限,对db1有读的权限 use test db.createUser({   user:
"chuck",   pwd: "123",   roles: [     {role: "readWrite", db: "test"},     {role: "read", db: "db1"}       ] })

添加权限认证

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

登录权限认证

use admin
db.auth("root", "123")

谁创建的用户必须在谁那里登录

use test
db.auth("root", "123") # error

登录

# MySQL
mysql -u root -p 123

mongo -u "root" -p "123"

mongo -u "root" -p "123" --authenticationDatabase "admin"

mongo -u "tank" -p "123" 
mongo -u "tank" -p "123" --authenticationDatabase "test"

python连接MongoDB:

import pymongo

client = pymongo.MongoClient("mongodb://root:123@localhost:27017/")

print(client)
# use test
test = client['test']

# test.user
user = test['user']
print(user)

#插入数据
user0 = {
    "_id": 1,
    "name": "chuck",
    "age": 18
}

user.insert(user0)

print(list(user.find({
    "name": "chuck"
})))

数据库操作:(_id:主键)

--

增:

db.user  # test.user
db.user.info  # test.user.info
db.user.xxx   # test.user.xxx
# 集合的名字限制在121个字节 

删:

db.user.drop()

db.user.deleteOne({ 'age': 250 })

#2、删除国家为China的全部
db.user.deleteMany( {'addr.country': 'China'} )

#3、删除全部
db.user.deleteMany({})

查:

# 查看集合 ----> 查看表
show tables
show collections


# 数据类型
int 
str
数组
文档  字典
True
null  None
浮点型

正则 /^tank.*?nb$/i
new Date()
ObjectId()

use t1
db.data1.insert({
    "pattern": /^tank.*?nb$/i,
    "date": new Date(),
    "id": ObjectId()
})

db.data1.find()

# 文档操作:
MySQL:
    行记录

MongDB:
    文档
    
    
增:
MySQL:
    insert table名 字段 value('tank', age, sex)

use test
# 方式一:
db.user.insert({
    "_id": 1,
    "name": "天王盖地虎",
    "age": 250,
    "sex": "female"
})

# 方式二:
user0 = {
    "_id": 2,
    "name": "天王盖地虎2",
    "age": 20,
    "sex": "male"
}

db.user.insert(user0)


# 插入多条
user1={
    "_id":1,
    "name":"tank",
    "age":10,
    'hobbies':['music','read','dancing'],
    'addr':{
        'country':'China',
        'city':'GuangZhou'
    }
}

user2={
    "_id":2,
    "name":"egon",
    "age":20,
    'hobbies':['music','read','run'],
    'addr':{
        'country':'China',
        'city':'ShanDong'
    }
}


user3={
    "_id":3,
    "name":"jason",
    "age":30,
    'hobbies':['music','drink'],
    'addr':{
        'country':'China',
        'city':'AnHui'
    }
}

user4={
    "_id":4,
    "name":"kevin",
    "age":40,
    'hobbies':['music','read','dancing','tea'],
    'addr':{
        'country':'China',
        'city':'ShanDong'
    }
}

user5={
    "_id":5,
    "name":"nick",
    "age":50,
    'hobbies':['music','read',],
    'addr':{
        'country':'China',
        'city':'SH'
    }
}

db.user.insertMany([user1, user2, user3, user4, user5])

db.user.find().pretty()

查:
# 比较运算符
Mysql:
    = , !=, >, <, >=, <=
    
MongoDB:
# = 
1.select * from db1.user where id = 1;
db.user.find({"name": "tank"})

# !=  $ne
# 2.select * from db1.user where id != 1;

db.user.find({
    "_id": {
        "$ne": 1
    }
})

# >   "$gt"
# 3.select * from db1.user where id > 2;
db.user.find({
    "_id": {
        "$gt": 2
    }
})

# <   "$lt" 
# 4.select * from db1.user where age < 30;
db.user.find({
    "age": {
        "$lt": 30
    }
})

# >=  "$gte"
# 5.select * from db1.user where id >= 2;
db.user.find({
    "_id": {
        "$gte": 2
    }
})


# <=  "$lte"
# 6.select * from db1.user where id <= 5;
db.user.find({
    "_id": {
        "$lte": 5
    }
})

# 逻辑运算符
 $and, $or, $not
 
# Mysql:
select * from db1.user where id >= 3 and id <= 4;
select * from db1.user where id >=3 and id <=4 and age > 20;
 
# MongoDB:
db.user.find({
    "_id": {"$gte": 3, "$lte": 4}
})

db.user.find({
    "_id": {"$gte": 3, "$lte": 4},
    "age": {"$gt": 20}
})

db.user.find({
    "$and": [
    {
        "_id": {"$gte": 3, "$lte": 4},
        "age": {"$gt": 20}
    }
    ]
})

# select * from db1.user where id >=0 and id <=2 or  id >= 4 or name = "egon";
# not ---> and  --->  or
db.user.find({
    "$or": [
        {"name": "egon"},
        {"_id": {"$gte": 0, "$lte": 2}},
        {"_id": {"$gte": 4}}
    ]
})

# $mod取余
# select * from db1.user where id % 2 =1;
db.user.find({
    "_id": {
    "$mod": [2,1]
    }
})

db.user.find({
    "_id": {
    "$mod": [2,0]
    }
})


# 找到id取余不为1
db.user.find({
    "_id": {
        "$not": {"$mod": [2,1]}
    }
})

# 成员运算
$in $nin
# 有egon与kevin名字的
db.user.find({
    "name":{"$in": ["egon", "kevin"]}
})

# 没有tank名字的
db.user.find({
    "name":{"$nin": ["tank"]}
})

# 正则
select * from db1.user where name regexp "^ke.*?(g|n)$";
db.user.find({"name": /^ke.*?(g|n)$/i})

# 布尔值
 select name, age from db1.user where name regexp "^ke.*?(n|g)$";
 
# 查询语法
db.user.find(
    {
     查询条件
    },
    
    {
     查看的内容
    },
    {
     其它
    }
)
 
db.user.find(
    {
    "name": /^ke.*?(g|n)$/i
    },
    
    {
      "_id": 0,
      "name": 1,
      "age":1
    }
)
 
db.user.find({
            "hobbies":{"$all":["music", "read"]}
})


db.user.find({
    "hobbies.0":"music"
})

db.user.find(
        {},
        {
            "_id": 0,
            "name": 0,
            "age": 0,
            "addr": 0,
            "hobbies": {"$slice": -2}
        }
) 

db.user.find(
        {},
        {
            "_id": 0,
            "name": 0,
            "age": 0,
            "addr": 0,
            "hobbies": {"$slice": [0, 2]}
        }
) 


db.user.find({"addr.city": "GuangZhou"})


# 1 升序   -1 降序
db.user.find().sort({"_id": 1})

db.user.find().sort({"_id": -1})

# 杂项
db.t5.insert({"a":10, "b": 20})
db.t5.insert({"a":10, "b": null})
db.t5.insert({"a":10,})

db.t5.find({})

改:

Mysql:
    update db1.t1 set age=84 where name="egon"
    
MongoDB:
db.table.update(
    条件,
    修改字段,
    其他参数
)

db.user.update(
    {"name": "egon"},
    {"age": 84}
)

db.user.update(
    {"name": "kevin"},
    {"$set": {"age": 84, "name": "kevin_武大郎"}}
)

db.user.update(
    {"_id": {"$gt": 1}},
    {"$set": {"age": 250}},
    {"multi": true}
)

# 其它  默认是false
"multi":true  # 批量
"upsert":true  # 有则更新,无则新增

# 
db.user.update(
        {"name":"kevin_武大郎"},
        {"$set":{"addr.country":"Japan"}}
)

# 修改数组的
db.user.update(
        {"name":"kevin_武大郎"},
        {"$set":{"hobbies.1":"Piao"}}
    )

# 删除字段
db.user.update(
        {"name":"kevin_武大郎"},
        {"$unset":{"hobbies":""}}
)

# 递增递减
db.user.update(
        {},
        {"$inc":{"age":1}},
        {"multi":true}
)

db.user.update(
        {},
        {"$inc":{"age":-1}},
        {"multi":true}
)

# $push 添加
db.user.update(
        {"name":"jason"},
        {"$push":{"hobbies":"piao"}},
        {"multi":true}
    )


# $pop  删除  -1 指的是 第一个  1指的是最后一个  先进后出
db.user.update(
        {"name":"jason"},
        {"$pop":{"hobbies": 1}},
        {"multi":true}
)

# $each循环
db.user.update(
        {"name":"nick"},
        {"$push":{"hobbies":{"$each":["纹身","抽烟"]}}},
        {"multi":true}
)

# $pull  按条件删
db.user.update(
        {"name":"nick"},
        {"$pull":{"hobbies": "纹身"}},
        {"multi":true}
)

# 创建一个空数组
db.t3.insert({"urls":[]})

db.t3.update(
        {},
        {"$addToSet":{"urls":{"$each":[
            "http://www.baidu1.com",
            "http://www.baidu2.com",
            "http://www.baidu3.com",
            "http://www.baidu4.com",
            "http://www.baidu5.com"
        ]}}},
        {"multi":true}
    )

 

posted @ 2019-03-12 20:03  ChuckXue  阅读(164)  评论(0编辑  收藏  举报