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, 查库名

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

2, 查集合名(相当于mysql中的表)

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

3, 查数据

所有数据
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,查找条目(返回符合条件的整条数据)

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

6, 正则查询

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方法会返回一个值 对应数据库中的_id

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

2, 插入多条数据

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, 插入指定id

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)
posted @ 2018-07-24 15:25  ops_sylar  阅读(160)  评论(0编辑  收藏  举报