pymongo

pymongo 使用

鏈接
# authMechanism傳輸協議,
# authSource認證庫,管理員須要對admin作認證,才能操做其餘db
# use_db, use_col,操做數據的庫和集合
def db_connected(db='news_spider', col=None,):
    uri = "mongodb://root:gtl1023@192.168.1.200/?authSource=admin&authMechanism=SCRAM-SHA-1"
    client = MongoClient(uri)
    use_db = client[db]
    if col is not None:
        use_col = use_db[col]
        return use_col
    return use_db
查詢

1, 查庫名mysql

db = db_connected()
for i in db.collection_names():print(i)

2, 查集合名(至關於mysql中的表)sql

db = MongoClient(uri)
for i in db.list_database_names():print(i)

3, 查數據mongodb

全部數據
col = db_connected(col='test')
for i in col.find(): print(i)

4,指定字段查詢(顯示指定的key-value,將要顯示的key設置爲1)數據庫

for i in col.find({},{'news_time': 1, 'news_link': 1, 'news_author' : 1, 'news_source':1}): print(i)

5,查找條目(返回符合條件的整條數據)ide

myquery = {'news_time': '2018-07-23'}
for i in col.find(myquery): print(i)

6, 正則查詢code

myquery = {'news_title': { '$regex': '^EOS'}}   #查詢全部標題以EOS開始的新聞
for i in col.find(myquery): print(i)

7, 返回結果限制(若是條目太多,能夠屢次返回,每次限制多少條)排序

myquery = {'news_title': { '$regex': '^EOS'}}
for i in col.find(myquery).limit(2): print(i)
插入數據

1, 插入單條數據,insert_one方法會返回一個值 對應數據庫中的_idit

test_data = {'name':'tom', 'job': 'ops'}
col = db_connected(col='test')
res = col.insert_one(test_data)
print(res.inserted_id)

2, 插入多條數據io

test_list = [{'name':'tom', 'job': 'ops'},{'name':'jerry', 'job': 'dev'}]
col = db_connected(col='test')
res = col.insert_many(test_list)
print(res.inserted_ids)

3, 插入指定idtest

est_list = [{'_id':100, 'name':'tom', 'job': 'ops'},{'_id':99, 'name':'jerry', 'job': 'dev'}]
col = db_connected(col='test')
res = col.insert_many(test_list)
print(res.inserted_ids)
修改數據

1, 修改單條(默認修改找到的第一條)

col = db_connected(col='test')
myquery = {'name':'tom'}
new_val = {'$set':{'name':'tomson'}}
col.update_one(myquery,new_val)
for i in col.find():print(i)

2, 修改全部符合條件的值

col = db_connected(col='test')
myquery = {'name':'tom'}
new_val = {'$set':{'name':'tomson'}}
col.update_many(myquery,new_val)
for i in col.find():print(i)
排序,默認正序, 參數輸入-1取反
col = db_connected(col='test')
for i in col.find().sort('name', -1):print(i)
刪除數據

1, 刪除指定單條

col = db_connected(col='test')
myquery = {'job':'dev'}
col.delete_one(myquery)
for i in col.find():print(i)

2, 刪除多條

col = db_connected(col='test')
myquery = {'job':'ops'}
col.delete_many(myquery)
for i in col.find():print(i)

3, 刪除集合中全部數據

col = db_connected(col='test')
col.delete_many({})
for i in col.find():print(i)

4, 刪除集合自己

col = db_connected(col='test')
col.drop()
db = db_connected()
for i in db.collection_names():print(i)
相關文章
相關標籤/搜索