首页 / 操作系统 / Linux / Python MongoDB相关操作
-------------------数据库操作------------------------????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})