MongoDB

1.连接数据库

import pymongo
client = pymongo.MongoClient(host='localhost',port=27017) # client = pymongo.MongoClient('mongodb://loaclhost:27017/')
2.指定数据库

db=client.test                     #  db=client['test']

3.指定集合
collection
= db.students # collection = db['students']
4.插入数据

student = {
    'id':'20170303',
    'name':'Bob',
    'age':25,
    'gender':'male'
}

result = collection.insert(student)
print(result)       #返回_id值


插入多条数据
student1 = {
    'id':'20170606',
    'name':'Bob',
    'age':20,
    'gender':'male'
}

student2 = {
    'id':'20170707',
    'name':'Mike',
    'age':25,
    'gender':'male'
}
result = collection.insert([student1,student2])
print(result)       #返回数据库id值

目前官方推荐使用
result = collection.insert_one(student)   插入单条记录
result = collection.insert_many([student1,student2])   插入多条记录
print(result.inserted_id)   返回数据库id值
5.查询

插入数据后我们可以利用 find_one() 或 find() 方法进行查询,find_one() 查询得到是单个结果,find() 则返回一个生成器对象。

result = collection.find_one({'name': 'Mike'})
print(result)

对于多条数据的查询,我们可以使用 find() 方法,例如在这里查找年龄为 20 的数据

results = collection.find({'age': 20})
print(results)
for result in results:
    print(result)

查询大于20岁的
results = collection.find({'age': {'$gt': 20}})

results = collection.find({'name': {'$regex': '^M.*'}})    #正则匹配

7.计数

要统计查询结果有多少条数据,可以调用 count() 方法,如统计所有数据条数:

count = collection.find().count()
print(count)

或者统计符合某个条件的数据:

count = collection.find({'age': 20}).count()
print(count)
8.排序
9.偏移

10.更新
方法一:
condition = {'name': 'Kevin'}      #条件
student = collection.find_one(condition)     #查询
student['age'] = 25          #修改
result = collection.update(condition, student) #写入  #建议用 result = collection.update(condition, {'$set': student})
print(result)

另外 update() 方法其实也是官方不推荐使用的方法,在这里也分了 update_one() 方法和 update_many() 方法,用法更加严格,第二个参数需要使用 $ 类型操作符作为字典的键名
方法二:
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 26
result = collection.update_one(condition, {'$set': student})
print(result)
print(result.matched_count, result.modified_count)   #然后调用 matched_count 和 modified_count 属性分别可以获得匹配的数据条数和影响的数据条数。
10.删除

result = collection.remove({'name': 'Kevin'})
print(result)

另外依然存在两个新的推荐方法,delete_one() 和 delete_many() 方法

result = collection.delete_one({'name': 'Kevin'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age': {'$lt': 25}})
print(result.deleted_count)

 

posted @ 2019-05-21 13:43  Yzc_start  阅读(112)  评论(0编辑  收藏  举报