连接 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)
来源: http://www.bubuko.com/infodetail-2912374.html