Python mongo 数据库插入、查询、更新、删除某个字段等

____tz_zspython

建立 mongo 数据库对象

from pymongo import MongoClient

# 地址,端口
mongo_client = MongoClient(mongod_host, mongod_port) # 建立 MongoClient 对象,(string格式,int格式)
mongo_db = mongo_client[mongodb_db_name] # MongoDB 中可存在多个数据库,根据数据库名称获取数据库对象(Database)
mongo_db.authenticate(mongodb_user, mongodb_passwd) # 登陆认证

db_collection=mongo_db[collection_name] # 每一个数据库包含多个集合,根据集合名称获取集合对象(Collection)

登陆成功:
True
登陆失败:
pymongo.errors.OperationFailure: Authentication failed.web

插入数据 insert

将要插入的数据:正则表达式

records = [{ 
 
  "_id": "2019zhangsan", "name": "ZhangSan", "grade": { 
 
  "math": 80, "english": 82, "chinese": 73}},
           { 
 
  "_id": "2019lisi", "name": "LiSi", "grade": { 
 
  "math": 90, "english": 83, "chinese": 74}},
           { 
 
  "_id": "2019wangwu", "name": "WangWu", "grade": { 
 
  "math": 80, "english": 88, "chinese": 75}}]

insert()

insert(self, doc_or_docs, manipulate=True, check_keys=True, continue_on_error=False, **kwargs)
db_collection.insert() # 弃用,DEPRECATED - Use :meth:insert_one or :meth:insert_many instead.mongodb

insert_one()

insert_one(self, document, bypass_document_validation=False)数据库

result = db_collection.insert_one(document=records[0])
print(result)  # <pymongo.results.InsertOneResult object at 0x7fbb1ca41b90>
print(result.inserted_id)  # 2019zhangsan

insert_many()

insert_many(self, documents, ordered=True, bypass_document_validation=False)svg

result = db_collection.insert_many(documents=records)
print(result)  # <pymongo.results.InsertManyResult object at 0x7f2997632f80>
print(result.inserted_ids)  # ['2019zhangsan', '2019lisi', '2019wangwu']

_id 重复报错

插入一条
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: xxxx.tzzs_test index: id dup key: { : “2019zhangsan” }
插入多条
pymongo.errors.BulkWriteError: batch op errors occurred函数

查询数据 find

find(self, *args, **kwargs):
find_one(self, filter=None, *args, **kwargs) 全部参数与 find() 相同,但会无视 limit 参数,返回一条记录或 None。post

filter

经常使用的过滤操做ui

https://juejin.im/post/5addbd0e518825671f2f62ee  
https://docs.mongodb.com/manual/reference/operator/query/  
$lt小于{'age': {'$lt': 20}}  
$gt大于{'age': {'$gt': 20}}  
$lte小于等于{'age': {'$lte': 20}}  
$gte大于等于{'age': {'$gte': 20}}  
$ne不等于{'age': {'$ne': 20}}  
$in在范围内{'age': {'$in': [20, 23]}}  
$nin不在范围内{'age': {'$nin': [20, 23]}}  
$regex匹配正则表达式{'name': {'$regex': '^M.*'}}name以M开头  
$exists属性是否存在{'name': {'$exists': True}}name属性存在  
$type类型判断{'age': {'$type': 'int'}}age的类型为int  
$mod数字模操做{'age': {'$mod': [5, 0]}}年龄模5余0  
$text文本查询{'$text': {'$search': 'Mike'}}text类型的属性中包含Mike字符串  
$where高级条件查询{'$where': 'obj.fans_count == obj.follows_count'}自身粉丝数等于关注数

无 filter 条件,将查询全部的数据。函数返回游标对象 Cursor,使用 for 循环遍历完后,cursor.alive 将变为 False。spa

cursor = db_collection.find()  # Cursor
print(cursor.alive)
for i in cursor:
    print(i)
print(cursor.alive)
""" True {u'grade': {u'math': u'80', u'chinese': u'73', u'english': u'82'}, u'_id': u'2019zhangsan', u'name': u'ZhangSan'} {u'grade': {u'math': u'90', u'chinese': u'74', u'english': u'83'}, u'_id': u'2019lisi', u'name': u'LiSi'} {u'grade': {u'math': u'80', u'chinese': u'75', u'english': u'88'}, u'_id': u'2019wangwu', u'name': u'WangWu'} False """

filter条件:exists 根据字段是否存在来过滤

cursor = db_collection.find(filter={ 
 
  "grade.math": { 
 
  "$exists": True}})
print(cursor.alive)
for i in cursor:
    print(i)
print(cursor.alive)
""" True {u'grade': {u'math': u'80', u'chinese': u'73', u'english': u'82'}, u'_id': u'2019zhangsan', u'name': u'ZhangSan'} {u'grade': {u'math': u'90', u'chinese': u'74', u'english': u'83'}, u'_id': u'2019lisi', u'name': u'LiSi'} {u'grade': {u'math': u'80', u'chinese': u'75', u'english': u'88'}, u'_id': u'2019wangwu', u'name': u'WangWu'} False """

filter条件:regex 正则匹配字段的名称

cursor = db_collection.find(filter={ 
 
  "grade.math": { 
 
  "$regex": "8.*"}})  # Cursor
print(cursor.alive)
for i in cursor:
    print(i)
print(cursor.alive)
""" True {u'grade': {u'math': u'80', u'chinese': u'73', u'english': u'82'}, u'_id': u'2019zhangsan', u'name': u'ZhangSan'} {u'grade': {u'math': u'80', u'chinese': u'75', u'english': u'88'}, u'_id': u'2019wangwu', u'name': u'WangWu'} False """
cursor = db_collection.find(filter={ 
 
  "name": { 
 
  "$regex": ".*S.*"}})
print(cursor.alive)
for i in cursor:
    print(i)
print(cursor.alive)
""" True {u'grade': {u'math': u'80', u'chinese': u'73', u'english': u'82'}, u'_id': u'2019zhangsan', u'name': u'ZhangSan'} {u'grade': {u'math': u'90', u'chinese': u'74', u'english': u'83'}, u'_id': u'2019lisi', u'name': u'LiSi'} False """

sort

查询时,按照必定的规则排序。
(key, direction)组成的list,指定排序的key和方向,能够同时存在多个(key, direction)对,优先级依次下降
~pymongo.cursor.Cursor.sort
sort=[("_id", -1)]

更新数据 update

update 不知能够用 set 等操做来插入或更新,还能够用 unset 来删除特定的字段。

update_one()

update_one(self, filter, update, upsert=False, bypass_document_validation=False, collation=None)

""" {u'grade': {u'math': 80, u'chinese': 73, u'english': 82}, u'_id': u'2019zhangsan', u'name': u'ZhangSan'} {u'grade': {u'math': 90, u'chinese': 74, u'english': 83}, u'_id': u'2019lisi', u'name': u'LiSi'} {u'grade': {u'math': 80, u'chinese': 75, u'english': 88}, u'_id': u'2019wangwu', u'name': u'WangWu'} """
result = db_collection.update_one(filter={ 
 
  "grade": { 
 
  "$exists": True}}, update={ 
 
  "$set": { 
 
  "grade.aaa": 77}})
print(result)
print(result.matched_count)  # 1
print(result.modified_count)  # 1
""" {u'grade': {u'aaa': 77, u'math': 80, u'chinese': 73, u'english': 82}, u'_id': u'2019zhangsan', u'name': u'ZhangSan'} {u'grade': {u'aaa': 77, u'math': 90, u'chinese': 74, u'english': 83}, u'_id': u'2019lisi', u'name': u'LiSi'} {u'grade': {u'aaa': 77, u'math': 80, u'chinese': 75, u'english': 88}, u'_id': u'2019wangwu', u'name': u'WangWu'} """
result = db_collection.update_one(filter={ 
 
  "grade.aaa": { 
 
  "$exists": True}}, update={ 
 
  "$unset": { 
 
  "grade.aaa": ""}}, upsert=False)
print(result)  # <pymongo.results.UpdateResult object at 0x7f6ef4c8fcf8>
print(result.matched_count)  # 1
print(result.modified_count)  # 1

update_many()

update_many(self, filter, update, upsert=False, bypass_document_validation=False, collation=None)

""" {u'grade': {u'math': 80, u'chinese': 73, u'english': 82}, u'_id': u'2019zhangsan', u'name': u'ZhangSan'} {u'grade': {u'math': 90, u'chinese': 74, u'english': 83}, u'_id': u'2019lisi', u'name': u'LiSi'} {u'grade': {u'math': 80, u'chinese': 75, u'english': 88}, u'_id': u'2019wangwu', u'name': u'WangWu'} """
result = db_collection.update_many(filter={ 
 
  "grade": { 
 
  "$exists": True}}, update={ 
 
  "$set": { 
 
  "grade.aaa": 77}})
print(result)
print(result.matched_count)  # 3
print(result.modified_count)  # 3
""" {u'grade': {u'aaa': 77, u'math': 80, u'chinese': 73, u'english': 82}, u'_id': u'2019zhangsan', u'name': u'ZhangSan'} {u'grade': {u'aaa': 77, u'math': 90, u'chinese': 74, u'english': 83}, u'_id': u'2019lisi', u'name': u'LiSi'} {u'grade': {u'aaa': 77, u'math': 80, u'chinese': 75, u'english': 88}, u'_id': u'2019wangwu', u'name': u'WangWu'} """
result = db_collection.update_many(filter={ 
 
  "grade.aaa": { 
 
  "$exists": True}}, update={ 
 
  "$unset": { 
 
  "grade.aaa": 1}}, upsert=False)
print(result)  # <pymongo.results.UpdateResult object at 0x7f6ef4c8fcf8>
print(result.matched_count)  # 3
print(result.modified_count)  # 3
""" {u'grade': {u'math': 80, u'chinese': 73, u'english': 82}, u'_id': u'2019zhangsan', u'name': u'ZhangSan'} {u'grade': {u'math': 90, u'chinese': 74, u'english': 83}, u'_id': u'2019lisi', u'name': u'LiSi'} {u'grade': {u'math': 80, u'chinese': 75, u'english': 88}, u'_id': u'2019wangwu', u'name': u'WangWu'} """
相关文章
相关标签/搜索