mongoDB是由C++编写的分布式文档数据库。
内部使用类似于Json的bson格式。
中文手册https://www.w3cschool.cn/mongodb/
组件 | 文件名 |
---|---|
Server | mongod.exe |
Router | mongos.exe |
Client | mongo.exe |
MonitoringTools | mongostat.exe,mongotop.exe |
importExportTools | mongodump.exe,mongorestore.exe,mongoexport.exe,mongoimport.exe |
MiscellaneousTools | bsondump.exe,mongofiles.exe,mongooplog.exe,mongoperf.exe |
$ pwd
/d/Application/mogodb/package/mongodb4.0/bin
gdy@gdy MINGW64 /d/Application/mogodb/package/mongodb4.0/bin
$ ./mongod.exe
2019-08-13T22:01:34.963+0800 I STORAGE [main] Max cache overflow file size custom option: 0
2019-08-13T22:01:35.408+0800 I CONTROL [main] Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'
2019-08-13T22:01:35.412+0800 I CONTROL [initandlisten] MongoDB starting : pid=20852 port=27017 dbpath=D:\data\db\ 64-bit host=gdy
2019-08-13T22:01:35.413+0800 I CONTROL [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2019-08-13T22:01:35.413+0800 I CONTROL [initandlisten] db version v4.0.12
2019-08-13T22:01:35.413+0800 I CONTROL [initandlisten] git version: 5776e3cbf9e7afe86e6b29e22520ffb6766e95d4
2019-08-13T22:01:35.413+0800 I CONTROL [initandlisten] allocator: tcmalloc
2019-08-13T22:01:35.413+0800 I CONTROL [initandlisten] modules: none
2019-08-13T22:01:35.413+0800 I CONTROL [initandlisten] build environment:
2019-08-13T22:01:35.413+0800 I CONTROL [initandlisten] distmod: 2008plus-ssl
2019-08-13T22:01:35.413+0800 I CONTROL [initandlisten] distarch: x86_64
2019-08-13T22:01:35.413+0800 I CONTROL [initandlisten] target_arch: x86_64
2019-08-13T22:01:35.413+0800 I CONTROL [initandlisten] options: {}
2019-08-13T22:01:35.434+0800 I STORAGE [initandlisten] exception in initAndListen: NonExistentPath: Data directory D:\data\db\ not found., terminating
2019-08-13T22:01:35.434+0800 I NETWORK [initandlisten] shutdown: going to close listening sockets...
2019-08-13T22:01:35.434+0800 I CONTROL [initandlisten] now exiting
2019-08-13T22:01:35.434+0800 I CONTROL [initandlisten] shutting down with code:100
gdy@gdy MINGW64 /d/Application/mogodb/package/mongodb4.0/bin
$
D:\data\db\
--bind_ip ip
逗号分隔ip地址。默认localhost--bing_ip_all
绑定所有本地ip地址--port port
端口,默认27017--dbpath path
数据路径,缺省为\data\db\
。windows下缺省就是当前盘符的根目录--logpath path
指定日志文件,替代stdout,说明默认是控制台打印日志-f file
指定配置文件,yaml格式注册wiendows服务
mongodb配置使用YAML格式
嵌套使用缩进晚餐,不支持Tab等制表符,支持空格
冒号后要有空格
Yaml参考https://www.w3cschool.cn/iqmrhf/dotvpozt.html
配置mongoing.com/docs/reference/configuration-options.html
在mongodb安装目录新建配置文件mongodb.yml。内容如下:
systemLog:
destination: file
path: "D:/Application/mogodb/package/mongodb4.0/mongod.log"
logAppend: true
storage:
dbPath: "D:/Application/mogodb/package/mongodb4.0/db"
net:
bindIp: 127.0.0.1
port: 27017
D:/Application/mogodb/package/mongodb4.0/db
文件夹选项
windows下注册为服务的命令如下,使用了配置文件:
mongod.exe -f "D:/Application/mogodb/package/mongodb4.0/mongod.yml" --serviceName mongod --serviceDisplayName mongo --install
去掉配置文件中的配置日志信息部分。这样日志将会显示在控制台
storage:
dbPath: "D:/Application/mogodb/package/mongodb4.0/db"
net:
bindIp: 127.0.0.1
port: 27017
$ pwd
/d/Application/mogodb/package/mongodb4.0/bin
gdy@gdy MINGW64 /d/Application/mogodb/package/mongodb4.0/bin
$ ./mongod.exe -f ../mongodb.yml
$ bin/mongo.exe
MongoDB shell version v4.0.12
help 打开帮助
show dbs 查看当前库
use blog 有就切换过去,没有就创建后切换过去。刚创建的并不在数据库列表中,需要写入数据后才能看到
db 查看当前数据库
db.users.insert({user:"tom",age:20}) db指代当前数据库;users集合名
mongodb://gdy:[email protected]:27017/test
from pymongo import MongoClient
# client = MongoClient(host="127.0.0.1",port=27017) #客户端连接
client = MongoClient("mongodb://127.0.0.1:27017")
print(client)
# db = client.blog
db = client["blog"] #指定数据库
print(db)
# users = db["users"]
users = db.users #集合
print(users)
MongoDB | RDBMS |
---|---|
Database | Database |
Table | Collection |
Row | Document |
Column | Field |
Join | Embedded Document嵌入文档或Reference引用 |
Primary Key | 主键(MongoDB提供了Key为_id) |
_id
唯一标识一个文档。没有没有显示指明该属性,会自动生成一个Objectld类型的_id
属性。_id
的值from pymongo import MongoClient
from pymongo.results import InsertOneResult
from pymongo.collection import Collection
# client = MongoClient(host="127.0.0.1",port=27017) #客户端连接
client = MongoClient("mongodb://127.0.0.1:27017")
db = client["blog"] #指定数据库
users:Collection = db.users #集合
user1 = {"id":1,"name":"ben","age":20}
# users.insert(user1) #已经过期
#单条插入
x:InsertOneResult = users.insert_one(user1)
print(type(x),x)
print(x.inserted_id)
user2 = {"id":257,"name":"tom","age":32}
user3 = {"id":258,"name":"jerry","age":18}
#批量插入
result = users.insert_many([user2,user3])
print(result.inserted_ids)
#[ObjectId('5d539433c1b3dcb23654814d'), ObjectId('5d539433c1b3dcb23654814e')]
#大小写敏感
user4 = {"id":"3","name":"tom","age":20,"Name":"tommy"}
x = users.insert_one(user4)
print(x.inserted_id)
ObjectID由12个字节组成
根据上面的objectID(5d539433c1b3dcb23654814d)验证
import datetime
t = "5d539433c1b3dcb23654814d"[:8] #时间戳提取
print(t)
x = int.from_bytes(bytearray.fromhex(t),"big")
print(hex(x),x)
print(datetime.datetime.fromtimestamp(x))
# 也可以使用函数获取
import bson
dat = bson.ObjectId("5d539433c1b3dcb23654814d").generation_time
print(dat,dat.timestamp())
00 00 05 82 d7 35 00 00 00 07 5f 69 64 00 5d 45
35
表示文档二精制数据长度07
表示MongoDB中特殊数据类型ObjectID5f 69 64
,ascii码_id
57 be 12 f2 bf 14 48 c7 43 de 10 69 64 00 01 01
5d 45 57 be 12 f2 bf 14 48 c7 43 de
,ObjectId(‘5d4557be12f2bf1448c743de’)_id的值10 69 64
,10表示类型int-32,69 64
是ascii码id0101
小端模式,十进制25700 00 02 6e 61 6d 65 00 04 00 00 00 74 6f 6d 00
02
表示数据类型UTF-8 String6e 61 6d 65
表示字符串name04
,表示字符串长度74 6f 6d 00
,表示字符串tom和结束符10 61 67 65 00 20 00
10
,表示数据类型int-3261 67 65
,表示字符串age20
,表示十进制32.
和$
有特别的意义,只有在特定环境下才能使用_
开头的键是保留的,例如:_id
from pymongo import MongoClient
from pymongo.collection import Collection
from bson.objectid import ObjectId
client = MongoClient("mongodb://127.0.0.1:27017")
db = client["blog"] #指定数据库
users:Collection = db.users #集合
# 查询
result = users.find_one({"name":"tom"})
print(type(result),result)
# 使用key查询
result2 = users.find_one({"_id":ObjectId("5d539433c1b3dcb23654814d")})
print(type(result2),result2)
#查不到,返回None
result3 = users.find_one({"name":"tommy"})
print(type(result3),result3)
from pymongo import MongoClient
from pymongo.collection import Collection
client = MongoClient("mongodb://127.0.0.1:27017")
db = client["blog"] #指定数据库
users:Collection = db.users #集合
# 多条查询
results = users.find({"name":"tom"})
print(type(results))
print(results)
print("- "*30)
for x in results:
print(type(x),x)
比较符号 | 含义 | 示例 |
---|---|---|
$lt |
小于 | {"age":{"$lt":20}} |
$gt |
大于 | {"age":{"$gt":20}} |
$lte |
小于等于 | {"age":{"$lte":20}} |
$gte |
大于等于 | {"age":{"$gte":20}} |
$ne |
不等于 | {"age":{"$ne":20}} |
$eq |
等于,可以不用增符号 | {"age":{"$eq":20}} |
$in |
在范围内 | {"age":{"$in":[20,23]}} |
$nin |
不在范围内 | {"age":{"$nin":[20,30]]}} |
逻辑符号 | 含义 | 示例 |
---|---|---|
$and |
与 | {"$and":[{"name":"tom"},{"age":{"$gt":20}}]} |
$or |
或 | |
$not |
非 |
元素 | 含义 | 示例 |
---|---|---|
$regex |
文档中字段内容匹配 | {"name":{"$regex":"^t"}} |
$mod |
取模 | {"age":{"$mod":[10,2]}} 模10余2 |
from pymongo import MongoClient
from pymongo.collection import Collection
client = MongoClient("mongodb://127.0.0.1:27017")
db = client["blog"] #指定数据库
users:Collection = db.users #集合
# 统计
# 被弃用
# count = users.find({"age":{"$gt":10}}).count()
#求出age>10的数量
count = users.count_documents({"age":{"$gt":10}})
print(count) #返回结果4
from pymongo import MongoClient
from pymongo.collection import Collection
import pymongo
client = MongoClient("mongodb://127.0.0.1:27017")
db = client["blog"] #指定数据库
users:Collection = db.users #集合
# 排序
results = users.find().sort("age",pymongo.DESCENDING) #降序
print(*list(results),sep="\n")
print("- "*30)
results2 = users.find().sort(
[
("name",pymongo.DESCENDING),#name降序排列
("age",pymongo.ASCENDING) #age升序
]
)
print(*list(results2),sep="\n")
from pymongo import MongoClient
from pymongo.collection import Collection
client = MongoClient("mongodb://127.0.0.1:27017")
db = client["blog"] #指定数据库
users:Collection = db.users #集合
# 分页
results = users.find()
print(*list(results),sep="\n")
print("- "*30)
results1 = users.find().skip(2) #跳过前2个
print(*list(results1),sep="\n")
print("- "*30)
results2 = users.find().skip(1).limit(2) #跳过前1个最多显示2个
print(*list(results2),sep="\n")
print("- "*30)
更新操作符 | 含义 | 示例 |
---|---|---|
$inc |
对给定字段数字值增减 | {"$inc":{"age":-5}} 对age的值-5 |
$set |
设置字段值,如果字段不存在则创建 | {"$set":{"gender":"M"}} |
$unset |
移除字段 | {"$unset":{"Name":""}} |
_id
外的所有字段from pymongo import MongoClient
from pymongo.collection import Collection
client = MongoClient("mongodb://127.0.0.1:27017")
db = client["blog"] #指定数据库
users:Collection = db.users #集合
print(*list(users.find()),sep="\n")
print("- "*30)
# 更新,将name为tom的结果中第一行文档中age增加5
result = users.update_one({"name":"tom"},{"$inc":{"age":5}})
print(type(result),result)
print(result.matched_count,result.modified_count)
print("- "*30)
print(*list(users.find()),sep="\n")
from pymongo import MongoClient
from pymongo.collection import Collection
client = MongoClient("mongodb://127.0.0.1:27017")
db = client["blog"] #指定数据库
users:Collection = db.users #集合
print(*list(users.find()),sep="\n")
print("- "*30)
# 更新,将name为tom的字段都添加一个gender等于m的属性
result = users.update_many({"name":"tom"},{"$set":{"gender":"M"}})
print(type(result),result)
print(result.matched_count,result.modified_count)
print("- "*30)
print(*list(users.find()),sep="\n")
print("- "*30)
# 更新,将有name为tom的文档中包含Name属性的删除
result = users.update_many({"name":"tom"},{"$unset":{"Name":""}})
print(type(result),result)
print(result.matched_count,result.modified_count)
print("- "*30)
print(*list(users.find()),sep="\n")
_id
字段外的所有字段from pymongo import MongoClient
from pymongo.collection import Collection
client = MongoClient("mongodb://127.0.0.1:27017")
db = client["blog"] #指定数据库
users:Collection = db.users #集合
print(*list(users.find()),sep="\n")
print("- "*30)
# 替换文档
result = users.replace_one({"name":"tom"},{"id":200,"name":"sam"})
print(type(result),result)
print("- "*30)
print(*list(users.find()),sep="\n")
from pymongo import MongoClient
from pymongo.collection import Collection
from pymongo.results import DeleteResult
client = MongoClient("mongodb://127.0.0.1:27017")
db = client["blog"] #指定数据库
users:Collection = db.users #集合
print(*list(users.find()),sep="\n")
print("- "*30)
# 删除age为20的文档,只删除一条
result:DeleteResult = users.delete_one({"age":20})
print(type(result),result.deleted_count)
print("- "*30)
print(*list(users.find()),sep="\n")
# 删除所有存在age字段的文档
result2:DeleteResult = users.delete_many({"age":{"$exists":True}})
print(type(result2),result2.deleted_count)
print("- "*30)
print(*list(users.find()),sep="\n")