数据库笔记(MongoDB)(3)

Python与MongoDB交互

 

创建管理员

> use admin 
switched to db admin
> db
admin
> db.createUser({user:'admin',pwd:'123456',roles:[{role:'userAdminAnyDatabase',db:'admin'}]})
Successfully added user: {
    "user" : "admin",
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        }
    ]
}
> exit
View Code

 

创建普通用户

> use mydb
switched to db mydb
> db.createUser({user:'guest',pwd:'123456',roles:[{role:'readWrite',db:'mydb'}]})
Successfully added user: {
    "user" : "guest",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "mydb"
        }
    ]
}
> db.auth('guest','123456')
1
View Code

 

删除用户

 

db.dropUser("guest")

 

 

 

连接Mongodb

import pymongo

# 建立MongoDB数据库连接
# connection = pymongo.Connection('192.168.198.128', 27017)

# 如果设置了权限,注意xxx用户权限要可以cover到后面使用到的数据库
# client = pymongo.MongoClient('192.168.198.128', 27017, username='guest', password='123456')
client = pymongo.MongoClient('192.168.198.128',27017)

# 连接所需数据库,test为数据库名
db=client.test
# db_name = 'test'
# db = client[db_name]

# 连接所用集合,也就是我们通常所说的表,test为表名
# db和collection都是延时创建的,在添加Document时才真正创建
collection=db.test
View Code

 

添加数据

first_name = ["","","","",""]
second_name = ["","","","",""]
third_name = ["","","","",""]
data = [
    {"_id":int("1000"+str(i)),
     "name":random.choice(first_name)+
            random.choice(second_name)+
            random.choice(third_name),
     "age":random.randint(16,60),
     "high":random.randint(170,190),
     "list":list(random.randint(1,200) for i in range(10))
    } for i in range(5)
]
try:
    for record in data:
        collection.save(record)
except pymongo.errors.DuplicateKeyError:
    print('record exists')
except Exception as e:
    print(e)
View Code

 

删除数据

 

collection.delete_many({'age':{'$gt':20,'$lt':30}})   #删除所有满足条件的文档,删除_id大于6,小于100
collection.delete_one({'age':20})                     #删除一条满足条件的文档,删除_id=6
#collection_set01.delete_many({})                     #删除整个集合

 

更新数据

collection.replace_one({'_id': 10000}, {'name': '王宝宝'})                         #replace_one用指定的key-value替代原来所有的key-value
collection.update_one({"_id": {'$lt': 10008}}, {'$set': {"age": "19"}})           #update_one更新已经对应的key-value,其它不变
collection.update_many({'_id': {'$gt': 10007}}, {'$set': {'age': '50'}})          #同上,能够update所有符合匹配条件的文档

 

查询数据

print('\n------------身高小于180:')
print(type(collection.find({'high':{'$lt':180}})))
for row in collection.find({'high':{'$lt':180}}):
    print(row)
print(type(collection.find_one({'high':{'$lt':180}})))
print('use find_one:',collection.find_one({'high':{'$lt':180}})['high'])
print('use find_one:',collection.find_one({'high':{'$lt':180}}))

print('\n------------查询特定键')
print('------------查询身高大于170,并只列出_id,high和age字段(使用列表形式_id默认打印出来,可以使用{}忽视_id):')
for row in collection.find({'high':{'$gt':170}},projection=['high','age']):
    print(row)

print('\n------------skip参数用法')
for row in collection.find({'high':{'$gt':170}},['high','age'],skip=1):
    print(row)
for row in collection.find({'high':{'$gt':170}},['high','age']).skip(1):
    print(row)

print('\n------------limit参数用法')
for row in collection.find({'high':{'$gt':170}},['high','age'],limit=1):
    print(row)

print('\n------------用{}描述特定键')
for row in collection.find({'high':{'$gt':170}},{'high':1,'age':1,'_id':False}):
    print(row)

print('\n------------多条件查询')
print(collection.find_one({'high':{'$gt':10},'age':{'$lt':26,'$gt':10}}))


# for u in db.users.find({"age":{"$nin":(23, 26, 32)}}):
# print u
# select * from users where age not in (23, 26, 32)

print('\n------------count')
print(collection.find({"age":{"$gt":20}}).count())

print('\n------------条件或')
print('大于等于29或者小于23')
for row in collection.find({"$or":[{"age":{"$lte":23}}, {"age":{"$gte":29}}]}):
    print(row)

print('\n------------exists')
for row in collection.find({'age':{'$exists':True}}):
    print('age exists',row) # select * from 集合名 where exists 键1
for row in collection.find({'age':{'$exists':False}}):
    print('age not exists',row)

print('\n------------正则表达式查询')
print('method 1')
for row in collection.find({'name':{'$regex':r'.*暖.*'}}):
    print(row)
print('method 2')
import re
Regex = re.compile(r'.*爱.*',re.IGNORECASE)
for row in collection.find({'name':Regex}):
    print(row)

print('\n------------使用sort排序(文档中没有排序的字段也会打印出来,表示最小)')
print('------------age 升序')
for row in collection.find().sort([["age",pymongo.ASCENDING]]):
    print(row)
print('------------age 降序')
for row in collection.find().sort([("age",-1)]):
    print(row)
print('------------age升序,high升序')
for row in collection.find().sort((("age",pymongo.ASCENDING),("high",pymongo.ASCENDING))):
    print(row)
print('------------age升序,high降序')
for row in collection.find(sort=[("age",pymongo.ASCENDING),("high",pymongo.ASCENDING)]):
    print(row)

print('\n------------$all')
for row in collection.find({'list':{'$all':[77,117,165,37,57,49,178,90,3,166]}}):
    print(row)

print('\n------------$in')
for row in collection.find({'list':{'$in':[2,3,4]}}):
    print(row)

print('\n------------size=10')
for row in collection.find({'list':{'$size':10}}):
    print(row)
    
    
# print('-------------------$unset')
# print('$unset和$set相反表示移除文档属性')
# print('---before')
# for row in collection.find({'name': "张程芬"}):
#     print(row)
# collection.update({'name':'张程芬'},{'$unset':{'age':1}})
# print('---after')
# for row in collection.find({'name':'张程芬'}):
#     print(row)
View Code

 

 完整代码文件

import pymongo
import random



def add_data(collection):
    first_name = ["","","","",""]
    second_name = ["","","","",""]
    third_name = ["","","","",""]
    data = [
        {"_id":int("1000"+str(i)),
         "name":random.choice(first_name)+
                random.choice(second_name)+
                random.choice(third_name),
         "age":random.randint(16,60),
         "high":random.randint(170,190),
         "list":list(random.randint(1,200) for i in range(10))
        } for i in range(5)
    ]
    try:
        for record in data:
            collection.save(record)
    except pymongo.errors.DuplicateKeyError:
        print('record exists')
    except Exception as e:
        print(e)


def delete_data(collection):
    remove_before = collection.find()
    print('---------------delete before--------------------')
    for obj in remove_before:
        print(obj)

    collection.delete_many({'age':{'$gt':20,'$lt':30}})   #删除所有满足条件的文档,删除_id大于6,小于100
    collection.delete_one({'age':20})                     #删除一条满足条件的文档,删除_id=6
    #collection_set01.delete_many({})                     #删除整个集合
    remove_after = collection.find()

    print('---------------delete after--------------------')
    for obj in remove_after:
        print(obj)


def update_data(collection):
    collection.replace_one({'_id': 10000}, {'name': '王宝宝'})                         #replace_one用指定的key-value替代原来所有的key-value
    collection.update_one({"_id": {'$lt': 10008}}, {'$set': {"age": "19"}})           #update_one更新已经对应的key-value,其它不变
    collection.update_many({'_id': {'$gt': 10007}}, {'$set': {'age': '50'}})          #同上,能够update所有符合匹配条件的文档



def select_data(collection):

    print('\n------------身高小于180:')
    print(type(collection.find({'high':{'$lt':180}})))
    for row in collection.find({'high':{'$lt':180}}):
        print(row)
    print(type(collection.find_one({'high':{'$lt':180}})))
    print('use find_one:',collection.find_one({'high':{'$lt':180}})['high'])
    print('use find_one:',collection.find_one({'high':{'$lt':180}}))

    print('\n------------查询特定键')
    print('------------查询身高大于170,并只列出_id,high和age字段(使用列表形式_id默认打印出来,可以使用{}忽视_id):')
    for row in collection.find({'high':{'$gt':170}},projection=['high','age']):
        print(row)

    print('\n------------skip参数用法')
    for row in collection.find({'high':{'$gt':170}},['high','age'],skip=1):
        print(row)
    for row in collection.find({'high':{'$gt':170}},['high','age']).skip(1):
        print(row)

    print('\n------------limit参数用法')
    for row in collection.find({'high':{'$gt':170}},['high','age'],limit=1):
        print(row)

    print('\n------------用{}描述特定键')
    for row in collection.find({'high':{'$gt':170}},{'high':1,'age':1,'_id':False}):
        print(row)

    print('\n------------多条件查询')
    print(collection.find_one({'high':{'$gt':10},'age':{'$lt':26,'$gt':10}}))


    # for u in db.users.find({"age":{"$nin":(23, 26, 32)}}):
    # print u
    # select * from users where age not in (23, 26, 32)

    print('\n------------count')
    print(collection.find({"age":{"$gt":20}}).count())

    print('\n------------条件或')
    print('大于等于29或者小于23')
    for row in collection.find({"$or":[{"age":{"$lte":23}}, {"age":{"$gte":29}}]}):
        print(row)

    print('\n------------exists')
    for row in collection.find({'age':{'$exists':True}}):
        print('age exists',row) # select * from 集合名 where exists 键1
    for row in collection.find({'age':{'$exists':False}}):
        print('age not exists',row)

    print('\n------------正则表达式查询')
    print('method 1')
    for row in collection.find({'name':{'$regex':r'.*暖.*'}}):
        print(row)
    print('method 2')
    import re
    Regex = re.compile(r'.*爱.*',re.IGNORECASE)
    for row in collection.find({'name':Regex}):
        print(row)

    print('\n------------使用sort排序(文档中没有排序的字段也会打印出来,表示最小)')
    print('------------age 升序')
    for row in collection.find().sort([["age",pymongo.ASCENDING]]):
        print(row)
    print('------------age 降序')
    for row in collection.find().sort([("age",-1)]):
        print(row)
    print('------------age升序,high升序')
    for row in collection.find().sort((("age",pymongo.ASCENDING),("high",pymongo.ASCENDING))):
        print(row)
    print('------------age升序,high降序')
    for row in collection.find(sort=[("age",pymongo.ASCENDING),("high",pymongo.ASCENDING)]):
        print(row)

    print('\n------------$all')
    for row in collection.find({'list':{'$all':[77,117,165,37,57,49,178,90,3,166]}}):
        print(row)

    print('\n------------$in')
    for row in collection.find({'list':{'$in':[2,3,4]}}):
        print(row)

    print('\n------------size=10')
    for row in collection.find({'list':{'$size':10}}):
        print(row)


    # print('-------------------$unset')
    # print('$unset和$set相反表示移除文档属性')
    # print('---before')
    # for row in collection.find({'name': "张程芬"}):
    #     print(row)
    # collection.update({'name':'张程芬'},{'$unset':{'age':1}})
    # print('---after')
    # for row in collection.find({'name':'张程芬'}):
    #     print(row)



def main():
    client = pymongo.MongoClient('192.168.198.128', 27017, username='guest', password='123456')

    db = client.test

    collection = db.test

    add_data(collection)

    update_data(collection)

    select_data(collection)

    delete_data(collection)


if "__main__" == __name__:
    main()
View Code

 

输出结果

------------身高小于180:
<class 'pymongo.cursor.Cursor'>
{'_id': 10002, 'name': '赵爱风', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
{'_id': 10003, 'name': '李爱风', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
<class 'dict'>
use find_one: 172
use find_one: {'_id': 10002, 'name': '赵爱风', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}

------------查询特定键
------------查询身高大于170,并只列出_id,high和age字段(使用列表形式_id默认打印出来,可以使用{}忽视_id):
{'_id': 10001, 'age': 21, 'high': 186}
{'_id': 10002, 'age': 24, 'high': 172}
{'_id': 10004, 'age': 41, 'high': 182}

------------skip参数用法
{'_id': 10002, 'age': 24, 'high': 172}
{'_id': 10004, 'age': 41, 'high': 182}
{'_id': 10002, 'age': 24, 'high': 172}
{'_id': 10004, 'age': 41, 'high': 182}

------------limit参数用法
{'_id': 10001, 'age': 21, 'high': 186}

------------用{}描述特定键
{'age': 21, 'high': 186}
{'age': 24, 'high': 172}
{'age': 41, 'high': 182}

------------多条件查询
{'_id': 10001, 'name': '王鑫风', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}

------------count
4

------------条件或
大于等于29或者小于23
{'_id': 10001, 'name': '王鑫风', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
{'_id': 10003, 'name': '李爱风', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
{'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}

------------exists
age exists {'_id': 10000, 'name': '王宝宝', 'age': '19'}
age exists {'_id': 10001, 'name': '王鑫风', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
age exists {'_id': 10002, 'name': '赵爱风', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
age exists {'_id': 10003, 'name': '李爱风', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
age exists {'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}

------------正则表达式查询
method 1
method 2
{'_id': 10002, 'name': '赵爱风', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
{'_id': 10003, 'name': '李爱风', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}

------------使用sort排序(文档中没有排序的字段也会打印出来,表示最小)
------------age 升序
{'_id': 10001, 'name': '王鑫风', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
{'_id': 10002, 'name': '赵爱风', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
{'_id': 10003, 'name': '李爱风', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
{'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
{'_id': 10000, 'name': '王宝宝', 'age': '19'}
------------age 降序
{'_id': 10000, 'name': '王宝宝', 'age': '19'}
{'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
{'_id': 10003, 'name': '李爱风', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
{'_id': 10002, 'name': '赵爱风', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
{'_id': 10001, 'name': '王鑫风', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
------------age升序,high升序
{'_id': 10001, 'name': '王鑫风', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
{'_id': 10002, 'name': '赵爱风', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
{'_id': 10003, 'name': '李爱风', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
{'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
{'_id': 10000, 'name': '王宝宝', 'age': '19'}
------------age升序,high降序
{'_id': 10001, 'name': '王鑫风', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
{'_id': 10002, 'name': '赵爱风', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
{'_id': 10003, 'name': '李爱风', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
{'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
{'_id': 10000, 'name': '王宝宝', 'age': '19'}

------------$all

------------$in

------------size=10
{'_id': 10001, 'name': '王鑫风', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
{'_id': 10002, 'name': '赵爱风', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
{'_id': 10003, 'name': '李爱风', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
{'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
---------------delete before--------------------
{'_id': 10000, 'name': '王宝宝', 'age': '19'}
{'_id': 10001, 'name': '王鑫风', 'age': 21, 'high': 186, 'list': [133, 19, 191, 74, 113, 39, 95, 149, 91, 103]}
{'_id': 10002, 'name': '赵爱风', 'age': 24, 'high': 172, 'list': [37, 116, 190, 120, 15, 101, 95, 159, 43, 34]}
{'_id': 10003, 'name': '李爱风', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
{'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
---------------delete after--------------------
{'_id': 10000, 'name': '王宝宝', 'age': '19'}
{'_id': 10003, 'name': '李爱风', 'age': 31, 'high': 170, 'list': [170, 167, 197, 184, 58, 83, 79, 122, 149, 11]}
{'_id': 10004, 'name': '李程明', 'age': 41, 'high': 182, 'list': [122, 1, 80, 145, 151, 114, 143, 56, 122, 100]}
View Code

 

 

 

参考博客:https://www.cnblogs.com/diaosir/p/6507178.html

 

posted @ 2018-07-30 16:26  luchun666  阅读(255)  评论(0编辑  收藏  举报