Post

0405MongoDB

MongoDB(p144)是一个NoSQL(Not Only SQL[不仅仅是SQL],泛指非关系型数据库)数据库

准备工作

安装MongoDB

1
2
3
4
5
6
7
brew tap mongodb/brew
brew install mongodb-community

#启动、停止、重启 MongoDB服务
brew services start mongodb-community
brew services stop mongodb-community
brew services restart mongodb-community

安装 PyMongo库:pip3 install pymongo

卸载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#在终端上执行以下步骤:

#1检查是否有任何 mongo 服务正在运行。
launchctl list | grep mongo

#2。
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist
rm -f ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist
launchctl remove homebrew.mxcl.mongodb-community

#3.杀死 mongod 进程(如果存在)。
kill -f mongod

#4.
brew uninstall mongodb-community
brew uninstall mongodb-database-tools
brew uninstall mongosh
brew untap mongodb/brew

#5.如果你手动安装了 MongoDB(没有 Homebrew),那么使用:
rm -rf <yourmongodb_folder>

#6.删除数据库文件。
rm -rf /usr/local/var/mongodb

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import pymongo

#1.链接
client = pymongo.MongoClient(host='localhost',port=27017) #或者以字符串形式 pymongo.MongoClient('mongodb://localhost:27017/')

#2.指定数据库
db=client.test#指定 test 数据库。或者 client['test']

#3.指定集合(collection,MongoDB的集合类似于关系型数据库中的表)
collection=db.students #或者 db['students']

#student1 = {'id': '20120001', 'name': 'Jordan','age': 20,'gender':'male'}
#student2 = {'id': '20120002', 'name': 'Kevin','age': 20,'gender':'male'}
#student3 = {'id': '20120003', 'name': 'Harden','age': 20,'gender':'male'}
#collection.insert_many([student1,student2,student3])

操作函数

一堆用json来封装的狗屎操作符,就不能设置个SQL 一样的DSL吗

目的指令实例其他
插入insert_one()插入一条数据
insert_many([])插入多条数据
collection.insert_one(student),返回 _id(唯一标识)
colection.insert_many([student1,student2])</span>
result.inserted_ids返回的是插入的_id数组
查询find_one({})查询返回单条数据
find({})查询返回多条数据
collection.find_one({‘name’: ‘Jordan’})

from bson.objectid import ObjectId
collection.find_one({‘_id’: ObjectId(‘xx’)})

collection.find({‘age’:20} ),返回Cursor
collection.find({‘age’:{‘$gte’:20}}),查找age>=20(比较符表
collection.find({‘name’:{‘$regex’:’^H.*’}}),正则表达式匹配 name 开头是H(评价查询操作符表
 
更新update_one(condition,{})只能更新一条数据
update_many(condition,{})
collection.update_one({‘name’:’Kevin’},newStudent),将原来的数据用新的完全替换掉
collection.update_one({‘name’:’Kevin’},{‘$set’:newStudent})

collection.update_many({‘age’:{‘$gt’:20}},{‘$inc’:{‘age’:1}}),$inc自增操作符
update_one还有个参数upsert:更新或插入
$set操作符只更新newStudent中的字段(且如果更新字段旧值和新值相等则不会更新)

update_one返回{‘ok’:1/*代表执行成功*/,’nModified’:1/*影响行数*/,’n’:1,’updateExisting’:True}
代码访问:result.matched_count(匹配行数),result.modifyied_count(影响行数)
删除delete_one({})、remove({})删除一条数据
delete_many({})删除多条
collection.delete_one({‘name’:’Kevin’})
collection.delete_many({‘age’:{‘$lt’:25}})
代码访问:result.deleted_count(删除行数)
计数count()collection.find().count()
collection.find({‘age’:20}).count()
 
排序sort(field,)collection.find().sort(‘name’,pymongo.ASCENDING) 
偏移skip(n)collection.find().sort(‘name’,pymongo.ASCENDING).skip(2),偏移2位 
删除集合collection.drop()  
删除数据库db.dropDatabase()  

比较符表(p147)

符号含义实例
$lt小于{‘age’: {‘$lt’: 20}}
$lte小于等于{‘age’: {‘$lte’:20}}
$gt大于{‘age’: {‘$gt’: 20}}
$gte大季等手{‘age’: {‘$gte’: 20}}
$eq等于{“field”:{‘$eq’:value}}
$ne不等于{“field”:{‘$ne’:value}}
$in在范围内{‘age’: {‘$in’:[20, 23]}}
$nin不在范围内{‘age’: {‘$nin’:[20, 23]}}

评价查询操作符表(p148)

符号含义实例实例含义
$mod数字模操作{‘age’: {‘$mod’: [5, o]}}age%5=0
$regex匹配正则表达式{‘name” :”$regex aM.”}name以M为开头
$text类型的属性中包含{‘$text’: {“$search”: “Mike’}}text类型的属性中包含Mike字符串
$where高级条件查询{‘$where”:”obj.fans count= obj.follows count”}判读obj.fans count= obj.follows count
$exists属性是否存在{‘name” :”$exists”:True}存在 name 属性
$type类型判断{‘age’: {‘$type’: int}}age 的类型为int

逻辑查询操作符

符号含义实例
$and逻辑与
{ $and: [ { <exp1> }, { <exp2> }, … ] }
find( { $and: [ { quantity: { $lt: 15 } }, { price: 10 } ] } )
$or逻辑或
{ $or: [ { <exp1> }, { <exp2> }, … ] }
find( { $or: [ { quantity: { $lt: 15 } }, { price: 10 } ] } )
$nor逻辑或非
{ $nor: [ { <exp1> }, { <exp2> }, … ] }
find( { $nor: [ { price: 3.99 }, { sale: true } ] } )
$not{ field: { $not: { } } }find( { price: { $not: { $lt: 3.99 } } } ),price>=3.99
This post is licensed under CC BY 4.0 by the author.