MongoEngine User Documentation:对mongodb进一步封装,使用ODM(object document mapping对象文档映射)
一、基础概念:
文档数据库:
MongoDB中的一条记录就是一个文档,是一个数据结构,由字段和值对组成。
{name:"John", age:21}
区分大小写 key唯一,不可重复 文档可嵌套 键值对有序
集合:
集合就是一组文档,文档类似关系型数据库中的行,集合类似关系型数据库中的表
集合的命名:
1.不能是空字符串
2.不能包含 字符
3.不能使用system.的前缀(系统保留)
4.建议不使用保留字 $
5.用 . 分割不同和命名空间的子集合
数据库:
多个文档组成集合,多个集合组成数据库
二、使用命令行操作数据库(CRUD)
在命令行中定位到 bin 目录下,输入 mongo 进入数据库命令行
show dbs; # 展示所有数据库 use db_name # 选择使用的数据库,不存在的话就创建 db # 显示当前使用的数据库
Create(新增数据)
MongoDB中提供了以下方法来插入文档到一个集合:
db.collection_name.insert() # 向集合插入一个或多个文档.
db.collection_name.insertOne() # 向集合插入 多个 文档
db.collection_name.insertMany() # 向集合插入 一个 文档
db.users.insertMany(
[
{ name: "bob", age: 42, status: "A", },
{ name: "ahn", age: 22, status: "A", },
{ name: "xi", age: 34, status: "D", }
]
)
Read(查询数据)
选择集合中的所有文档
db.users.find()
指定查询过滤条件
db.users.find( { status: "A" } )
指定查询结果显示的数据(查询性别为male,显示其name,age,不显示id)
db.users.find({sex:"male"},{name:1,age:true,_id:0})
查询所有18岁的男生和16岁的女生的数据
db.students.find($or : [ { sex:'male', age:18 } , { sex:'female', age:16 }])