MongoDB基础

一、认识MongoDB

MongoDB简介
1.基于分布式文件存储的开源数据库系统。
2.旨在为WEB应用提供可扩展的高性能数据存储解决方案
3.将数据存储为一个文档,文档类似与Json格式
{
name:“space”,
age:16,
address: {city:“深圳”, country:“china”}
}

MongoDB数据模型

MongoDB基础

MongoDB进入与退出

MongoDB基础

二、库、集合操作

库级操作语句
显示所有库: show dbs
切换/创建数据库: use 数据库名称
查看所在库: db
删除库:db.dropDatabase()

集合操作语句
显示当前数据库的集合: show collections
创建集合: db.createCollection(name)
MongoDB基础
删除集合: db.集合名称.drop()

三、文档操作

添加文档(数据)
db.集合名称.insert(document)
每一条数据,就是一个document,就是一条json
例: db.student.insert({name:‘space’, age:18})
添加文档时,如果不指定_id参数
MongoDB会为文档分配一个唯一的ObjectId
例: db.student.insert({’_id’:1, name:‘space’, age:18})
添加多条文档
db.student.insert([
{name:‘karry’, sex:‘男’, age:16},
{name:’lucky’, sex:‘女’, age:18},
{name:’space‘, sex:’女’, age:18},
])

查询文档(数据)
db.集合名称.find([conditions])
查看集合中全部数据: db.student.find()
格式化显示: db.student.find().pretty()
查看满足条件的数据: db.student.find({name:‘space’})

噩梦条件
and条件 {KaTeX parse error: Expected 'EOF', got '}' at position 43: …sion1}, ...] }̲ or条件 {or:[{expression1}, {expression1}, …] }
and和or混用 db.table.find({KaTeX parse error: Expected '}', got 'EOF' at end of input: or:[{and:[{sex:‘女’}, {age:18}]},{KaTeX parse error: Expected '}', got 'EOF' at end of input: …ex:'男'}, {age:{gt:18}}]}]})
MongoDB基础

例子:db.user.find({‘age’: {’$ne’: 18}})

修改文档(数据)
db.集合名称.update(, , {multi:})
修改一条数据: db.table.update({sex:‘男’}, {age:20})
指定属性修改: { KaTeX parse error: Expected 'EOF', got '}' at position 15: set: {age:20} }̲ db.table.upd…set: {age:666, sex: ‘xx’}} )
更新集合中所有满足条件的文档: { multi: true }
db.table.update({sex:‘男’}, {$set:{sex:‘女’}}, { multi:true} )

删除文档(数据)
db.集合名称.remove(, {justOne:})
删除集合中所有的文档:
db.table.remove({})
删除集合中满足条件的所有文档:
db.table.remove({sex: ‘男’})
只删除集合中满足条件的第一条文档: { justOne: true }
db.table.remove({sex:‘男’}, { justOne:true} )

MongoDB基本使用总结

MongoDB基础

四、Python与MogoDB交互

pymongo
pip install pymongo
建立连接:client = pymongo.MongoClient()
指定数据库:db = client[数据库名]
指定集合:collection=db[集合名]

基本使用
1.查找文档: find()
2.添加文档:insert()
3.修改文档:update()
4.删除文档:remove()

注意要点
官方推荐我们使用如下的方法
查找一条文档: find_one()
查找所有:find()
添加一条文档:insert_on
添加多条:insert_many()
删除一条文档:delete_one
删除多条:delete_many()
修改一条文档: update_one
修改多条:update_many()

总结

MongoDB基础