MongoDB基础
- 数据库分类
- 关系型数据库
把复杂的数据结构归为简单的二元关系,类似于平常的表格。对于数据库操作全部建立在一个或多个关系表格上,通过对这些关联的数据表进行连接,分类,合并等来对数据实现管理。
现在常用的有mysql和oracle等。
- 非关系数据库
被称为NoSQL数据库,Not Only SQL,它在传统的关系型数据库进行了补充。相比于关系型数据库少了很多约束,各个文档集合没有特别紧密的联系,擅长超大数据规模的数据存储。
2.MongoDB
mongodb将数据存储为一个文档,由key-value组成。其中value支持:Duble,String,Object,Array,Date等。形如:
{
"name":"Tom",
"sex":"man",
"age":10
}
MongoDB分为四级存储:数据库db,文档集合collection(类似于table),文档document(类似于表的一条数据row),字段
常用命令:
创建数据库,没有自动创建: use dbname
查看现有数据库: show dbs
只有插入数据时才会创建数据库和集合:
> show dbs
admin 0.000GB
config 0.000GB l
ocal 0.000GB
> use dbTest1
switched to db shiyanlou
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
>db.firstcollection.insertOne({name:'Tom',sex:'man',age:10})
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
dbTest1 0.000GB
查看集合 : show collections
创建集合: db.createCollection("test2")
创建集合:
db.createCollection( <name>,
{ capped: <boolean>,
autoIndexId: <boolean>,
size: <number>,
max: <number>,
storageEngine:<document>,
validator: <document>,
validationLevel: <string>,
validationAction: <string>,
indexOptionDefaults: <document>,
viewOn: <string>, // Added in MongoDB 3.4
pipeline:<pipeline>, // Added in MongoDB 3.4
collation:<document>, // Added in MongoDB 3.4 writeConcern: <document>
} )
查询集合中的数据: db.test1.find()
插入多条数据:db.test1.insertMany([ {dict1},{dict2} ])
只插入一条: db.test1.insertOne({dict1})
删库删表:db.dropDatabase() db.test.drop()
美观:db.test.find().pretty()
更新: db.test.update({name:tome},{$set:{age:35}}) 把name为tome的age改为35,$set是一个操作符
db.test2,save({id:1}) 通过save函数插入数据,也可以对文档整体替换
查询: find({"name":"tom"}) find($or:[{"age":11},{"age",23}]) $or 实现或二者选一
删除: deleteOne({"age":1}) , deletMany({"age":1},{"age":2}) ,delect($or,[{dict1} , {dict2}])
使用python操作数据库
首先安装: pip install pymongo
"""
from pymongo import MongoClient
client = MongoClient(host="localhost",port=10323)
client.list_database_name() #查询MongoDB中的数据库
db = client.get_database("test") #使用test db
db.list_collection_name() #查collections
person = db.create_collection("person")
person.insert_one({"name":"李白","age":11})
person.insert_many({"name":”李四“,"age":12},{”name”:"zhangsan","age":11})
c=person.find()
from collections import Iterator
isinstance(c,Iterator)
result = list(c)
person.delete_one({"name":"zhangsan"})
person.drop()
""'
MongoDB中的一些操作符,$lt 小于,$gt 大于 ,$type 类型 , $or ..
查询条件:limit(),skip(), sort()..
索引:getIndex() creatIndex() ,totalIndexSize(),dropIndex()
聚合操作:
$match 类似于find()操作 + $project 标识显示数据有点像过滤
$limit+$skip 限制数据条数 + 跳过
$group分组 $max $min $sort
数据备份
mongodump -h dbhost -d dbname -o dbdirectory
恢复
mongorestore -h host -d dbname dir
部分集合备份
mongodump -h dbhost -d dbname -c collection -o dbdirectory
json文件备份与导入
mongoexport -h host -d dbname -c collection --type json/csv -o file
mongoimport -h host -d dbname -c collection --file file

浙公网安备 33010602011771号