python与mongodb_python 与mongodb 交互

连接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

添加数据

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)

删除数据

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(‘身高小于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('查询特定键')

print('查询身高大于170,并只列出_id,high和age字段(使用列表形式_id默认打印出来,可以使用{}忽视_id):')

for row in collection.find({'high':{'$gt':170}},projection=['high','age']):

print(row)

print('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('\limit参数用法')

for row in collection.find({'high':{'$gt':170}},['high','age'],limit=1):

print(row)

print('用{}描述特定键')

for row in collection.find({'high':{'$gt':170}},{'high':1,'age':1,'_id':False}):

print(row)

print('多条件查询')

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('count')

print(collection.find({"age":{"$gt":20}}).count())

print('\条件或')

print('大于等于29或者小于23')

for row in collection.find({"$or":[{"age":{"$lte":23}}, {"age":{"$gte":29}}]}):

print(row)

print('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('正则表达式查询')

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('使用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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值