pymongo-MongoDB

Docker 安装 MongoDB

docker pull mongo:latest
docker run -itd --name mongo -p 27017:27017 mongo --auth

参数说明:

-p 27017:27017 :映射容器服务的 27017 端口到宿主机的 27017 端口。外部可以直接通过 宿主机 ip:27017 访问到 mongo 的服务。

--auth:需要密码才能访问容器服务。

接着使用以下命令添加用户和设置密码,并且尝试连接。

$ docker exec -it mongo mongo admin

创建一个名为 admin,密码为 123456 的用户。

> db.createUser({ user:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'},"readWriteAnyDatabase"]});

尝试使用上面创建的用户信息进行连接。

> db.auth('admin', '123456')

安装PyMongo

pip install pymongo

MongoDB的URI格式如下:mongodb://用户名:密码@服务器IP或域名:端口

如果没有设置权限验证,则不需要用户名和密码

conn = pymongo.MongoClient('mongodb://45.10.110.77:27017')

要设置 pymongo 的超时功能,需要两个参数serverSelectionTimeoutMS,socketTimeoutMS,这两个参数的值的单位都是毫秒

import pymongo
conn = pymongo.MongoClient('mongodb://admin:[email protected]:27017',serverSelectionTimeoutMS=5000, socketTimeoutMS=5000)
database = conn.testDB
# database = conn['testDB']
collection = database.table1
# collection = database['table1']

# 使用Python批量插入数据
# collection.insert_many([
#    {'name': '王小二','age':21,'student':True,'address':'广州'},
#    {'name': '赵小三','age':20,'student':True,'address':'北京'},
#    {'name': '钱小四','age':21,'student':True,'address':'上海'},
#    {'name': '孙小五','age':20,'student':True,'address':'山东'},
#    {'name': '李小六','age': None,'student':True,'address':'河北'},
#    {'name': '欧阳小七','age':24,'student':False,'address':'杭州'},
#    {'name': '公孙小八','age':25,'student':False,'address':'广州'}
#  ])

# 插入一条数据
# collection.insert_one({'name': '刘小九','age':27,'student':False,'address':'合肥'})

# 查询第一条数据
x=collection.find_one({})
print(x,'\n')


# 查询所有数据
rows = collection.find()
for row in rows:
    print(row)

print('\n')
# collection.find({'字段名': {'基本符号': 边界值, '基本符号': 边界值}})

# 符号        含义          示例
# $lt       小于          {'age': {'$lt': 20}}
# $gt       大于          {'age': {'$gt': 20}}
# $lte      小于等于        {'age': {'$lte': 20}}
# $gte      大于等于        {'age': {'$gte': 20}}
# $ne       不等于     {'age': {'$ne': 20}}
# $in       在范围内        {'age': {'$in': [20, 23]}}
# $nin      不在范围内   {'age': {'$nin': [20, 23]}}

# 还可以进行正则匹配查询。例如,查询名字以M开头的学生数据,示例如下:
# results = collection.find({'name': {'$regex': '^M.*'}})
#
# 符号        含义                  示例                                                      示例含义
# $regex    匹配正则表达式     {'name': {'$regex': '^M.*'}}                            name以M开头
# $exists   属性是否存在          {'name': {'$exists': True}}                             name属性存在
# $type     类型判断                {'age': {'$type': 'int'}}                               age的类型为int
# $mod      数字模操作           {'age': {'$mod': [5, 0]}}                               年龄模5余0
# $text     文本查询                {'$text': {'$search': 'Mike'}}                          text类型的属性中包含Mike字符串
# $where    高级条件查询          {'$where': 'obj.fans_count == obj.follows_count'}       自身粉丝数等于关注数


rows = collection.find({'age':{'$lt':25,'$gt':21},
                        'name':{'$ne':'公孙小八'}})
for row in rows:
    print(row)

# 查询并对结果进行计数(更新到 4.0 版本,删除了 Cursor 类里的 count 方法)
# print(collection.find().count())


rows = collection.find().sort('age', 1) #其中方向为1表示升序,方向为**-1**表示降序
for row in rows:
    print(row)

# 更新一条
collection.update_one(
    {'name': '赵小三'},
    {'$set': {'address': '美国','age':60}})

# 更新所有
collection.update_many(
    {'name': '公孙小八'},
    {'$set': {'address': '英国','age':80}})

print('\n')
rows = collection.find().sort('age', 1).limit(5) #用limit()方法指定要取的结果个数
for row in rows:
    print(row)

# 删除第一个满足条件的数据
collection.delete_one({'age': 0})
# 删除所有满足条件的数据
collection.delete_many({'age': 0})```

你可能感兴趣的:(pymongo-MongoDB)