4.python mongodb
连接数据库,关闭连接:
import pymongo
def connection_db():
connection = pymongo.MongoClient("127.0.0.1", 27017) # 连接本地mongodb库
tdb = connection["ticket"] # 连接ticket库 也可写为 tdb = connection.ticket
return connection, tdb
def close_connection(connection):
connection.close() # 关闭连接
插入数据
def insert_one_data(tdb, collection, mongodb_data):
insert_x = tdb[collection].insert_one(mongodb_data) # 插入一条数据
return insert_x
def insert_many_data(tdb, collection, mongodb_data):
insert_x = tdb[collection].insert_many(mongodb_data) # 插入多条数据
return insert_x
if "__name__" == "main":
conn, tdb = connection_db()
res = insert_many_data(tdb, "ticket_info", data)
print(res._InsertManyResult__inserted_ids)
print( res.acknowledged)
close_connection(conn)
输出结果:
[ObjectId('5e6f45309057eba36a8b2471'), ObjectId('5e6f45309057eba36a8b2472'), ObjectId('5e6f45309057eba36a8b2473'), ObjectId('5e6f45309057eba36a8b2474'), ObjectId('5e6f45309057eba36a8b2475')]
True
查询数据:
from bson.objectid import ObjectId
## 若要查询mongodb自动生成的 _id 为查询条件 需要上面的ObjectId包
def select_one_data(tdb, collection, filters):
info = tdb[collection].find_one(filters) # 查询单条数据
return info
def select_all_data(tdb, collection, filters): # 查询多条数据,返回可迭代对象
info = tdb[collection].find(filters)
return info
if "__name__" == "main":
conn, tdb = connection_db()
filter = {"_id": ObjectId("5e6f45309057eba36a8b2471")}
res = select_all_data(tdb, "ticket_info", filter)
for item in res:
print(item)
close_connection()
输出结果:
{'_id': ObjectId('5e6f45309057eba36a8b2471'), 'item': 'journal', 'qty': 25, 'tags': ['blank', 'red'], 'dim_cm': [14, 21]}
查询条件:
需求条件 | 转化后示例 | 备注 |
---|---|---|
page=1, size=10 | tdb.ticket_info.find(filter).limit(size).skip( size * (page - 1) ) | |
qty > 40 | filter = {"qty": {"$gt": 40}} | |
qty = 25 | filter = {"qty": 25} | 或 filter = {"qty": {"$ne": 25}} |
qty < 40 | filter = {"qty": {"$lt": 40}} | |
qty >= 40 | filter = {"qty": {"$gte": 40}} | |
qty <= 40 | filter = {"qty": {"$lte": 40}} | |
qty in [25, 45] | filter = {"qty": {"$in": [25, 45]}} | |
qty berween 10 and 100 | filter = {"qty": {"$gte": 10, "$lte": 100}} | |
item like "%p%" | filter = {"item": {"$regex": "p"}} | 若是以p开头,"^p"; 若是以p结尾,"p$" |
若遇到{"name": 'z3', "child":[{"name": "zq", "age": 10}, {"name": "zw", "age": 11} ]}这样的数据类型,想要搜索列表中的数据 | filter = {"name.name": "zq"} | |
排序,倒叙为-1,正序为1,以上面数据类型为例 | query_result.sort("name", 1).sort( "name.age", -1) | 有多少个排序字段,加多少个sort方法 |
计算结果条数 | query_result.count() | query_result为find方法等等执行完成的对象 |
若想仅展示某些字段,或不返回某些字段 | find(filter, {"_id": 0, "qty": 1}) | find()的第一个参数是dict类型的检索条件,第二个参数为定义哪些字段展和禁止返回的,例子的信息是 "_id"字段不返回,"qty": 字段返回 |
注意:
skip(), limilt(), sort()三个放在一起执行的时候,执行的顺序是先 sort(), 然后是 skip(),最后是显示的 limit()。
更新数据:
def update_one_data(tdb, collection, my_query, new_values): # 更新一条数据
tdb[collection].update_one(my_query, new_values)
def update_many_data(tdb, collection, my_query, new_values): # 更新多条数据
tdb[collection].update_many(my_query, new_values)
删除数据:
def delete_one_data(tdb, collection, filters):
tdb[collection].delete_one(filters)
def delete_many_data(tdb, collection, filters):
tdb[collection].delete_many(filters)