python之pymongo

转载:https://juejin.im/post/5addbd0e518825671f2f62ee 

 

MongoDB是由C++语言编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,其内容存储形式类似JSON对象,它的字段值可以包含其他文档、数组及文档数组,非常灵活。

 

1. 连接mongo

import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)

或者

client = MongoClient('mongodb://localhost:27017/')

指定用户名+密码
client = MongoClient('mongodb://user:password@localhost:27017)

# 特殊字符处理, 用户名或密码中出现@或者:
@ ==》 %40
:==》 %3A

 

2. 指定数据库

db = client.test

or

db = client['test']

 

3. 指定集合

collection = db.test1

or

collection = db['test1']

 

4. 新增数据

# 添加单条

student = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}

result = collection.insert_one(student)
print(result)
print(result.inserted_id)

在MongoDB中,每条数据其实都有一个_id属性来唯一标识。如果没有显式指明该属性,MongoDB会自动产生一个ObjectId类型的_id属性。insert()方法会在执行后返回_id

 

# 添加多条

student1 = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}

student2 = {
    'id': '20170202',
    'name': 'Mike',
    'age': 21,
    'gender': 'male'
}

result = collection.insert_many([student1, student2])
print(result)
print(result.inserted_ids)

该方法返回的类型是InsertManyResult,调用inserted_ids属性可以获取插入数据的_id列表。

 

5. 查询数据

# 查询单条

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


# _id 查询

from bson.objectid import ObjectId

result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')})
print(result)



查询的结果存在则为字典,如果查询结果不存在,则会返回None

 

# 查询多条

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


返回结果是Cursor类型,它相当于一个生成器,我们需要遍历取到所有的结果,其中每个结果都是字典类型。

 

更多复杂查询条件:

#查询年龄大于20的用户
results = collection.find({'age': {'$gt': 20}})

 

 

 

# 查询名字以M开头的数据

results = collection.find({'name': {'$regex': '^M.*'}})

 

 

 

 

 

6. 计数

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

现在已经不推荐使用count了,可以使用document_count(). 用法和count是一样的

 

7. 排序

results = collection.find().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])

这里我们调用pymongo.ASCENDING指定升序。如果要降序排列,可以传入pymongo.DESCENDING

 

8. 偏移

# 利用skip()方法偏移几个位置,比如偏移2,就忽略前两个元素,得到第三个及以后的元素

results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])


# 还可以用limit()方法指定要取的结果个数

results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)
print([result['name'] for result in results])



# 值得注意的是,在数据库数量非常庞大的时候,如千万、亿级别,最好不要使用大的偏移量来查询数据,因为这样很可能导致内存溢出。此时可以使用类似如下操作来查询:

from bson.objectid import ObjectId
collection.find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}})


这时需要记录好上次查询的_id

 

9. 更新数据

#对于数据更新,我们可以使用update()方法,指定更新的条件和更新后的数据即可

condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update(condition, student)
print(result)

这里我们要更新name为Kevin的数据的年龄:首先指定查询条件,然后将数据查询出来,修改年龄后调用update()方法将原条件和修改后的数据传入。

{'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}
返回结果是字典形式,ok代表执行成功,nModified代表影响的数据条数。



我们也可以使用$set操作符对数据进行更新
result = collection.update(condition, {'$set': student})

这样可以只更新student字典内存在的字段。如果原先还有其他字段,则不会更新,也不会删除。而如果不用$set的话,则会把之前的数据全部用student字典替换;如果原本存在其他字段,则会被删除。

 

另外,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)

这里调用了update_one()方法,第二个参数不能再直接传入修改后的字典,而是需要使用{'$set': student}这样的形式,其返回结果是UpdateResult类型。然后分别调用matched_count和modified_count属性,可以获得匹配的数据条数和影响的数据条数。



condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)

这里指定查询条件为年龄大于20,然后更新条件为{'$inc': {'age': 1}},也就是年龄加1,执行之后会将第一条符合条件的数据年龄加1。


如果调用update_many()方法,则会将所有符合条件的数据都更新,示例如下:

condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)

 

10. 删除数据

删除操作比较简单,直接调用remove()方法指定删除的条件即可,此时符合条件的所有数据均会被删除。示例如下:
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)


delete_one()即删除第一条符合条件的数据,delete_many()即删除所有符合条件的数据。它们的返回结果都是DeleteResult类型,可以调用deleted_count属性获取删除的数据条数。


删除集合
collection.drop()

 

其他操作:

另外,PyMongo还提供了一些组合方法,如find_one_and_delete()find_one_and_replace()find_one_and_update(),它们是查找后删除、替换和更新操作,其用法与上述方法基本一致。

另外,还可以对索引进行操作,相关方法有create_index()create_indexes()drop_index()等。

关于PyMongo的详细用法,可以参见官方文档:http://api.mongodb.com/python/current/api/pymongo/collection.html

另外,还有对数据库和集合本身等的一些操作,这里不再一一讲解,可以参见官方文档:http://api.mongodb.com/python/current/api/pymongo/




 

posted @ 2019-10-15 09:46  X-Wolf  阅读(390)  评论(0编辑  收藏  举报