mongdb与redis四:python操作mongoDB

安装python mongoDB插件: pip install pymongo

一、连接服务器和数据库

from pymongo import MongoClient

# 连接服务器:
conn = MongoClient("localhost", 27017)

# 连接数据库:
db = conn.mydb

 

 

二、添加文档

# 获取集合
collection = db.student


# 添加文档:
collection.insert({"name": "jerry", "age": 20})
collection.insert([{"name": "bob", "age": 20}, {"name": "jason", "age":23])
conn.close()

 

 

三、查询文档

res = collection.find({"age": {"$gt": 18}})
# res:列表
conn.close()

 

统计:

res = collection.find({"age": {"$gt": 18}}).count()
# res:数字

 

根据id查询

from bson.Object import ObjectId  # 用于id查杀
res = collection.find({"_id": ObjectId("234234asdfas324")})

 

排序:

res = collection.find({"age": {"$gt": 18}}).sort("age")  # 升序
import pymongo
res = collection.find({"age": {"$gt": 18}}).sort("age", pymongo.DESCENDING)

 

分页:

res = collection.find({"age": {"$gt": 18}}).skip(3).limit(3)

 

四、更新文档

collection.update({"name": "jerry"}, {"$set": {"age": 25}})
conn.close()

 

五、删除文档

 

collection.remove({"name": "jerry"})
conn.close()

 

posted on 2018-08-16 20:32  myworldworld  阅读(91)  评论(0)    收藏  举报

导航