歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python MongoDB相關操作

Python MongoDB相關操作

日期:2017/3/1 10:50:30   编辑:Linux編程

-------------------數據庫操作------------------------

use dolphinop # 創建/切換數據庫

showdbs # 查看數據庫

showcollections # 查看數據庫中的表

db.dropDatabase() # 刪除數據庫

db.table_name.drop() # 刪除表

db.table_name.getIndexes(); # 查看索引

db.table_name.ensureIndex({'name':1}) # 建立索引(1或-1)

-------------------插入操作------------------------

插入數據:db.testcollection.insert({'name':'tompig,'age':25}); 說明:如果testcollection不存在則自動創建。

-------------------查詢操作------------------------

查詢所有數據:db.testcollection.find();

按條件查詢:db.testcollection.find({"name":"li"});

查詢統計:db.testcollection.find().count();

按條件查詢統計:db.testcollection.find({"name":"liu"}).count();

查詢固定條數記錄:db.testcollection.find().skip(1).limit(2); 從第二條開始查詢查詢2條記錄。

in查詢:db.testcollection.find({"age":{$in:["32","33"]}});

排序查詢:db.testcollection.find().sort({"age":-1});從大到小排序

db.user.find('this.age>"31"',{name:1}); 等同於SELECTname FROM user WHERE age >30

-------------------刪除操作------------------------

刪除所有數據:db.testcollection.remove({});

刪除一條符合條件的記錄:

(1)db.testcollection.remove({"age":"29"});

(2)db.testcollection.remove({"age":{$lt:"30"}});刪除age小於30的記錄

說明:$gt: > --(Greaterthan 的首字母)

$gte: >= --(Greaterthan or equal 的首字母)

$lt:< --(Lessthan 的首字母)

$lte:<= --(Lessthan or equal 的首字母)

$ne: != --(Notequal的首字母)

-------------------更新操作------------------------

db.testcollection.update({"name":"liu"},{$set:{"age":"35"}});

等同於sql的:updatetestcollection set 'age'='35' where name='liu';

-------------------函數使用------------------------

db.user.distinct("name",{"age":{$gt:"30"}});

等同mysql的selectdistinct("name") from user where age>"30";


15、pymongo查詢排序

mongo的排序:升序:db.feedbacks.find().sort({'id':1})

降序:db.feedbacks.find().sort({'id':-1})

pymongo的排序:db.feedbacks.find().sort('id') # 默認是升序

升序:db.feedbacks.find().sort('id',pymongo.ASCENDING)

將序:db.feedbacks.find().sort('id',pymongo.DESCENDING)

多列排序:db.feedbacks.find().sort([('id',pymongo.ASCENDING),('name',pymongo.DESCENDING)])

添加:db.feedbacks.insert({'id':1,'name':'wuxianglong'})

更新:db.feedbacks.update({'id':1},{'$set':{'name':'wuwenyuan'}})

刪除:db.feedbacks.remove() # 刪除所有數據

db.feedbacks.remove({'id':1})

Copyright © Linux教程網 All Rights Reserved