MongoDB

MongoDB

1.Mongodb的安装(有网址)

下载与教程网址

教程网址

2.Mongodb与sql的区别

sql mongodb
table collection
row documents
column filed

sql:

img

mongodb:

img

MongoDB的每个表(Collection)中存储的每条数据(Documents)都是一个一个的Json,Json中的每一个字段(Key)我们称之为:Field

就此我们引出了三个关键字,Collection也就是关系型数据库中"表"的概念,Documents就是"数据条目",Field就是"字段"

3.MongoDB的增删改查

3.1 增

3.1.1 use

use db 可以创建数据库并使用该数据库

image-20210725211549506

3.1.2 insert

db.collection.insert({})可以插入一条数据或多条数据(不过官方不支持,在窗口化界面可以使用)

image-20210725212017515

image-20210725212454190

官方推荐

3.1.3 insertOne

db.collection.insertOne({}) 只能一次插入一条数据,但返回结果不一样

image-20210725212111864

3.1.4 insertMany

db.collection.insertMany([{},{}]) 可一次性插入多条数据

image-20210725212231372

3.2 查

3.2.1 find

db.collection.find() 无条件查找:将该表(Collection)中所有的数据一次性返回

image-20210725212912380

db.collection.find({})条件查询

image-20210725213207108

3.2.2 findOne

db.collection.findOne()无条件查找一条数据,默认当前Collection中的第一条数据

image-20210725213050662

db.collection.findOne({})条件查询

image-20210725213341330

3.3 改

3.3.1 update

db.collection.update({条件},{$修改器:{数据}})

image-20210725214504270

官方推荐

3.3.2 updateOne

db.collection.updateOne({条件},{$修改器:{数据}}) 更新一条数据

3.3.3 updateMany

db.collection.updateMany({条件},{$修改器:{数据}}) 更新所有数据

3.4 删

3.4.1 remove

db.collection.remove({条件})

官方推荐:

3.4.2 deleteOne

db.collection.deleteOne({条件}) 删除一条数据

3.4.3 deleteMany

db.collection.deleteMany({条件}) 删除所有符合条件的数据

4.MongoDB的数据类型

Object  ID :Documents 自生成的 _id

String: 字符串,必须是utf-8

Boolean:布尔值,true 或者false (这里有坑哦~在我们大Python中 True False 首字母大写)

Integer:整数 (Int32 Int64 你们就知道有个Int就行了,一般我们用Int32)

Double:浮点数 (没有float类型,所有小数都是Double)

Arrays:数组或者列表,多个值存储到一个键 (list哦,大Python中的List哦)

Object:如果你学过Python的话,那么这个概念特别好理解,就是Python中的字典,这个数据类型就是字典

Null:空数据类型 , 一个特殊的概念,None Null

Timestamp:时间戳

Date:存储当前日期或时间unix时间格式 (我们一般不用这个Date类型,时间戳可以秒杀一切时间类型)

4.1 Object ID

image-20210725215536052

"_id" : ObjectId("60fd64a33e61dd6d268ae45f")

#"60fd64a3" 代指的是时间戳,这条数据的产生时间
#"3e61dd" 代指某台机器的机器码,存储这条数据时的机器编号
#"6d26" 代指进程ID,多进程存储数据的时候,非常有用的
#"8ae45f" 代指计数器,这里要注意的是,计数器的数字可能会出现重复,不是唯一的
#以上四种标识符拼凑成世界上唯一的ObjectID
#只要是支持MongoDB的语言,都会有一个或多个方法,对ObjectID进行转换
#可以得到以上四种信息

#注意:这个类型是不可以被JSON序列化的

4.2 String

image-20210725215857925

4.3 Boolean

image-20210725220054758

4.4 Integer

image-20210725220130251

4.5 Double

image-20210725220225650

4.6 Arrays

image-20210725220425066

4.7 Object

指python中的字典

image-20210725220635642

4.8 Null

image-20210725220807957

4.9 Timestamp

5. MongoDB 之 $关键字 及 $修改器 $set $inc $push $pull $pop

5.1 $

可以保存要修改数据的索引

image-20210726080256048

# 利用$保存修改数据的索引对数据进行修改

image-20210726081138161

5.2 $关键字

5.2.1 数字比较符

$lt   # 小于
$lte  # 小于等于
$gt   # 大于
$gte  # 大于等于
$eq   # 等于

db.collection.find({field:{$关键字:数字}})
db.collection.update({field:{$关键字:数字}},{})
'掌握一个其它几个也掌握了'

image-20210726082101898

5.2.2 查询关键字

$or db.collection.find({$or:[{name:1},{age:73}]})
$or db.collection.find({$and:[{name:1},{age:73}]})
$in db.collection.find({age:{$in:[1,2,3,4]}}) #符合其中一个条件即可
$all db.collection.find({hobby:{$all:[1,2,3,4]}}) #子集查询

5.3 $修改器

{
	"_id" : ObjectId("60a4f5f09f05ed36603d16ea"),
	"id" : 20,
	"name" : "wzh",
	"age" : 44,
    "info":{
         "weight" : 135,
         "long": 10
    },
	"hobby" : [
		1,
		2,
		3,
		4,
		"五",
		6,
		7,
		{
			"shenggao" : 140,
			"long" : 12
		},
		8
	]
}
$set 简单粗暴 {name:value} dict["name"]=value 
	
	$unset 简单粗暴的删除字段 {$unset:{name:1}}    del dict["name"]
	db.user_info.updateOne({age:44},{$unset:{age:1}})
	
	$inc 引用增加
	db.user_info.updateMany({},{$inc:{age:1}})  # age字段的值+1
	db.user_info.updateMany({},{$inc:{age:-20}})  # age字段的值每个都减20
    
	array操作
        $push 在array中追加一个新的元素 [].append(item)
        db.user_info.updateOne({name:"wzh"},{$push:{hobby:10}})

        $pull 在array中删除一个的元素 [].remove(item) [].pop(-1)
        db.user_info.updateOne({name:"wzh"},{$pull:{hobby:0}})
	
        $pop 不含索引 -1 从前往后  1 从后往前
        db.user_info.updateOne({name:"wzh"},{$pop:{hobby:1}})

5.4 Object 字典操作

db.user_info.updateOne({name:"wzh"},{$inc:{"info.weight":-5}})
db.user_info.updateOne({name:"wzh"},{$set:{"info.long":12.5}})

5.5 array + Object

db.user_info.updateOne({"hobby.shenggao":140},{$set:{"hobby.$.long":14}})

5.6 limit

db.user_info.find({}).limit(5)  # 选取数据从当前位置选择5个

5.7 skip 跳过

db.user_info.find({}).skip(2)  # 从0开始跳过2条数据为当前位置

5.8 sort

db.user_info.find({}).sort({ id:-1 })  # 根据ID进行排序 -1倒叙 1正序
db.user_info.find({}).limit(5).skip(5).sort({ id:-1 })	
// 优先级:sort>skip>limit

6. pymongo

6.1 安装模块

pip3 install pymongo

6.2 连接数据库

mongo_client = pymongo.MongoClient(host='127.0.0.1', port=27017)
MONGO = mongo_client['数据库']

6.3 查询数据

res = MONGO.collection(表).find({})  # 无条件查询所有数据,得到的是一个对象
<pymongo.cursor.Cursor object at 0x000001CF62E97888>
res = list(res)  # 转换成一个list,可以得到具体数据

若res中只有一条数据,可以按照取字典数据的方式取出数据
print(res['_id'])  # 60a3d6e6cf5ebe1a78a458d7
print(type(res['_id']))  # 该数据类型为ObjectId   <class 'bson.objectid.ObjectId'>

'取单条数据和取多条数据方法与find一致':
    # find_one  与数据库直接操作不一样,数据库为findOne,
    	res = MONGO.collection(表).find_one({条件})
    # find_many  与数据库直接操作不一样,数据库为findMany,
    	res = MONGO.collection(表).find_many({条件})

6.4 增加数据

res = MONGO.collection(表).insert_one({})  # 返回一个对象  
<pymongo.results.InsertOneResult object at 0x0000022C62653888>

res = MONGO.collection(表).insert_many([{},{}....])  # 同样返回一个对象
<pymongo.results.InsertManyResult object at 0x000001E4801CBD08>

6.5 修改数据

res = MONGO.user_info.update_one({"age":106},{"$set":{"long":20}})  # 在pymongo中可以使用$修改器,跟在数据库中的使用方法一致

res = MONGO.user_info.update_many({"age": 666}, {"$set": {"name": "pydwb", "age": 999}})

6.6 删除数据

res = MONGO.user_info.delete_one({"id": 20})

res = MONGO.user_info.delete_many({"name": 1})

6.7 skip sort limit

res = list(MONGO.user_info.find({}).limit(5))
print(len(res))

res = list(MONGO.user_info.find({}).limit(5).skip(5))
print(len(res), res)

res = list(MONGO.user_info.find({}).sort("age", pymongo.DESCENDING))  # 倒序排序
print(res)

res = list(MONGO.user_info.find({}).sort("age", pymongo.DESCENDING).skip(5).limit(2))
print(res)

7. bson

from bson import ObjectId
# 可以将字符串_id转化为mongodb中的ObjectID

str(res['_id']) --> ObjectId(str(res['_id']))  # 大概理解意思就行,可以用bson转换类型
posted @ 2023-03-04 22:11  w随风w  阅读(17)  评论(0编辑  收藏  举报