做者 changhao
邮箱 <wu_chang_hao@qq.com>
版本1.0
1). 下载安装包html
MongoDB 提供了可用于 32 位和 64 位系统的预编译二进制包,你能够从MongoDB官网下载安装,MongoDB 预编译二进制包下载地址:https://www.mongodb.com/downl...python
2). 安装mysql
指定安装路径,我这里安装在D:\software\mongodb,添加D:\software\mongodb\bin到环境变量中。正则表达式
3). 新建目录与文件夹sql
D:\software\mongodb\data\db D:\software\mongodb\log\mongod.log
4). 新建配置文件D:\software\mongodb\mongod.cfgmongodb
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). 制做系统服务shell
mongod --config "D:\software\mongodb\mongod.cfg" --bind_ip 0.0.0.0 --install
或者直接在命令行指定配置数据库
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). 启动MongoDB服务windows
net start MongoDB net stop MongoDB
7). 登陆MongoDB服务器
mongo 连接:http://www.runoob.com/mongodb/mongodb-window-install.html 当没有帐号密码登陆的时候,默认就是管理员登陆。,由于刚刚作系统服务install的时候没有指定 --auth(没有指定则没有权限认证这一说),(至关于mysql跳过受权表启动同样)
8). 建立有权限的用户
use admin db.createUser( { user: "root", # 这个root能够随便写 pwd: "123", roles: [{role: "root", db: "admin"}] # 权限,role是root说明是管理员, } ) use test db.createUser( { user: "test", pwd: "123", roles: [ {role: "readWrite", db: "test"}, # 针对test库有读写权限,操做本身的库有读写权限 {role: "read", db: "db1"} ] # 针对db1库读权限,操做其余库有读权限 } )
9). 重启数据库
mongod --remove mongod --config "D:\software\mongodb\mongod.cfg" --bind_ip 0.0.0.0 --install --auth # 或者 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). 从新登陆
# 方式一 mongo --port 27017 -u "root" -p "123" --authenticationDatabase "admin" # 方式二:在登陆以后用db.auth("帐号","密码")登陆 mongo use admin db.auth("root","123")
1). 安装依赖
yum install -y libcurl openssl
2). 下载MongoDB源码安装或yum管理器安装
# mongodb源码下载地址 https://www.mongodb.com/download-center#community # 或yum 安装 yum install -y mongodb
3). 建立数据库目录
# 建立目录,并设置用户权限 mkdir -p /var/lib/mongo mkdir -p /var/log/mongodb chown `whoami` /var/lib/mongo chown `whoami` /var/log/mongodb
4). 配置mongo服务参数, 容许全部ip访问
mongod --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongod.log --bind_ip_all --fork
5). 或者修改配置文件 /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). 后台启动
mongod -f /etc/mongod.conf &
7). 登陆mongodb
# 登陆 mongo # 建立数据库 test use test # 查看当前的数据库 db
# 链接到任何数据库config mongo 127.0.0.1:27017/config # 不链接任何数据库 mongo --nodb # 启动以后,在须要时运行new Mongo(hostname)命令就能够链接到想要的mongod了 conn = new Mongo('127.0.0.1:27017') db = conn.getDB('admin') # 显示当前数据库全部的数据库 show databases 或者 show dbs # 使用某个数据库,不存在则建立 use database # 删除数据库 db.dropDatabase()
在MongoDB中相关术语的解释和sql术语对应关系
SQL术语 | MongoDB术语 | 解释/说明 |
---|---|---|
database | database | 数据库 |
table | collection | 数据库表/集合 |
row | document | 数据库记录行/文档 |
column | field | 数据字段/域 |
index | index | 索引 |
table joins | 表链接,MongoDbB不支持 | |
primary key | primary key | 主键,MongoDB自动将_id字段设置主键 |
有一些数据库名是保留的,能够直接访问这些特殊做用的数据库
use test # 增长表内容 db.table1.insert({"a":1}) db.table2.insert({"b":2}) # 查看表 show collections 或者 show tables # 删除 db.user.info.help() # 查看帮助 db.user.info.drop() # 帮助, 不明白就help() db.table.help() # 举例
# 插入单条数据 user0 = { "name": "changhao", "age": "23", "hobbies": ['music', 'read', 'dancing'], "addr": { "country": 'China', "city": 'BJ', } } # 方式一 db.table1.insert(user0) # 方式二 db.table1.insertOne(user0) # 插入多条数据 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', } } # 方式一 db.table1.insertMany(user1, user2) # 方式二 db.table1.insertMany([user1, user2])
# 查看全部记录 db.table1.find() # 美化输出 db.table1.find().pretty() # 查找符合条件的全部 db.table1.find({"name": "changhao"}) # 查找符合条件的第一条 db.table1.findOne({"name": "changhao"})
# 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}})
#逻辑运算:$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} }) 或者 db.table1.find({"$and":[ {"_id":{"$gte":3,"$lte":4}}, # 一个字典就是一个条件 {"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 奇数 db.table1.find({"_id": {"$mod": [2, 1]}}) # 偶数, 取反 db.table1.find({"_id": {"$mod": [2, 1]}})
db.table1.find({ "name":/^jin.*?(g|n)$/i })
# 排序, 根据年龄排序, 1位正序, 1位倒序 db.table1.find().sort("age": 1) # 选取两条数据 db.table1.find().limit(2) # 跳过查询的数据的前2条 db.table1.find().skip(2) db.table1.sort({"age":-1}).skip(0).limit(2)
语法格式以下
db.collection.update( <query>, <update>, { upsert: <boolean>, multi: <boolean>, writeConcern: <document> } )
参数说明:
实战语句
# 1.覆盖式 db.table1.update({'age': 20}, {"name": "changhao"}) # 2. 这一种简单的更新,彻底替换匹配 var obj = db.table1.findOne({"_id": 2}) obj.username = obj.name + 'test' obj.age = 23 db.table1.update({"_id": 1}, obj)
设置
# 设置 $set 一般文档只会有一部分须要更新。可使用原子性的更新修改器,指定对文档中的某些字段进行更新。 更新修改器是种特殊的键,用来指定复杂的更新操做,好比修改、增长后者删除 # set name="changhao" where id = 2 db.table1.update({'_id': 2}, {"$set": {"name": "changhao", "age": 23}, {"upsert":true}) # 没有匹配成功则新增一条{"upsert":true} db.table1.update({'_id':2},{"$set":{"name":"changhao", "age":23}},{"upsert":true}) # 默认只改匹配成功的第一条,{"multi":改多条} db.table1.update({'_id':{"$gt":4}},{"$set":{"age":28}}) db.table1.update({'_id':{"$gt":4}},{"$set":{"age":38}},{"multi":true}) # 修改内嵌文档,把名字为test的人所在的地址国家改为Japan db.table1.update({'name':"test"},{"$set":{"addr.country":"Japan"}}) # 把名字为test的人的地2个爱好改为piao db.table1.update({'name':"test"},{"$set":{"hobbies.1":"piao"}}) # 删除test的爱好,$unset db.table1.update({'name':"test"},{"$unset":{"hobbies":""}})
# 增长和减小 $inc # 1.全部人年龄增长一岁 db.table1.update({}, { "$inc":{"age":1} }, { "multi":true } ) # 2.全部人年龄减小5岁 db.user.update({}, { "$inc":{"age":-5} }, { "multi":true } )
# 删除多个中的第一个 db.table1.deleteOne({"age":8}) # 删除国家为China的所有 db.table1.deleteMany({"addr.country": "China"})
import pymongo client = pymongo.MongoClient("192.168.158.137", 27017) # 显示服务器上的全部数据库 dblist = client.database_names() print(dblist) # 打印信息:['admin', 'config', 'local', 'test'] # 链接数据库,获取库,若是库名存在,则使用,不存在建立 db = client['test']
# 增长单条 mydict = {"name": "changhao001", "age": 23} res = db.table1.insert_one(mydict) print(res.inserted_id) # 返回ObjectId对象 # 增长多条 mylist = [{"name": "changhao002", "age": 23}, {"name": "changhao003", "age": 23}] res = db.table1.insert_many(mylist) print(res.inserted_ids) # 返回ObjectId对象列表
查询一条语句
# 查询一条数据 res1 = db.table1.find_one({'name': 'changhao1'}) print(res1.items()) # 查看匹配的数据内容
查询集合中的全部数据或多条
# 查询集合中的全部数据或多条 res2 = db.stu.find({}) # 查询全部记录 res3 = db.stu.find({"age": 23})
高级查询
# 年龄大于20岁的 myquery = {"age": {"$gt": 20}} res = db.table1.find(myquery)
正则表达式查询
# 读取 name 字段中第一个字母为 "c" 的数据 myquery = {"name": {"$regex": "^c"}} res = db.table1.find(myquery) # 遍历出匹配的数据 for x in res: print(x)
查询结果排序,跳过, 截取条数
# 查询结果的排序,跳过,和截取 sort_res = list(db.table1.find().sort("age", pymongo.DESCENDING)) # 查询全部结果,并根据年龄的降序排序 skip_res = list(db.table1.find().skip(2)) # 查询全部结果,并过滤掉前两条 limit_res = list(db.table1.find().limit(2)) # 查询全部结果,并截取前两条 # 分页效果 pagination_res = list(db.table1.find().sort("age", pymongo.DESCENDING).limit(2).skip(2))
# 查询到直接更新设置值 res = db.table1.update_one({'_id': 1}, {"$set": {"name": "changhao_update"}}) print(res.modified_count) # 查询到记录, 在字典中增长值 res = db.table1.find_one({"name": "changhao_update"}) res['age'] = 20 # 将值更新到记录中 res = db.table1.update_one({"name": "changhao_update"}, {"$set": res}) print(res.modified_count)
删除单条
# 删除结果中的一条 res = db.table1.delete_one({"name": "changhao_update"}) print(res.deleted_count)
删除多条
# 删除多条, 正则匹配的数据 query = {"name": {"$regex": "^c"}} res = db.table1.delete_many(query) print(res.deleted_count) # 删除全部 del_res = db.table1.delete_many({})