pymongo使用总结
0. 何为pymongo
pymongo是操作MongoDB的python模块
1、安装pymongo
# easy_install pymongo
2、连接mongodb
>>> import pymongo
>>> conn = pymongo.MongoClient(host=host,port=port,tz_aware=False)
3、获取数据库列表
>>> conn.database_names() [u'test1', u'test2', u'admin', u'local']
4、连接数据库
>>> db = conn.get_database("db_name")
5、权限验证
>>> db.authenticate('username', 'password')
True
6、获取聚集列表 (聚集的概念类似于关系型数据库中的表)
>>> db.collection_names() [u'account', u'role', u'item', u'online']
7、连接聚集
>>> account = db.get_collection("col_name")
8、查看聚集的一条记录
>>> account.find_one()
9、查看聚集的所有key (类似于关系型数据库中的字段)
>>> account.find_one().keys()
10、查看聚集的所有记录
>>> for i in account.find(): ... print i
11、查看记录总数
>>> account.find().count()
12、根据条件查询多条记录
>>> for i in account.find({"name": "xxx"}): ... print i
13、对查询结果进行排序 (默认升序ASCENDING)
>>> account.find().sort("name", pymongo.ASCENDING) >>> account.find().sort([("name", pymongo.ASCENDING), ("active_time", pymongo.DESCENDING)])
14、新增记录
>>> account.insert({"name": "mike", "active_time": "20130408"})
15、更新记录
>>> account.update({"name": "mike"}, {"$set": {"active_time": "20130408120000"}}) 注:如果数据中没有键-值"name": "mike", 会新增"active_time": "20130408120000"
16、删除记录 (不带条件表示全部删除)
>>> account.remove({"name": "mike"})
17. pycharm模糊不清匹配查询
方法1. import re {'xxx':re.compile('xxx')}
方法2. {'xxx':{'$regex':'xxx'}
18.and or
account.find({ $or: [ { title: {$regex: 'test'} }, { intro: {$regex: 'test'} } ] })
19. 案例
#! /usr/bin/env python # --*-- coding:utf-8 --*-- import pymongo import re host="**.**.**.**" port=27017 conn = pymongo.MongoClient(host=host,port=port,tz_aware=False) db_name = "test" log_name = "col" db_test = conn.get_database(db_name) col_col = db_test.get_collection(log_name) #print "db names:", conn.database_names() #print "col names:", db_test.collection_names() #print "one_line:", col_col.find_one() #print "one_line_keys:", col_col.find_one().keys() #col_col.insert({"message2":"hihihi", "msg":"123"}) #col_col.update({"message":"hello*3"}, {"$set":{"message":"hello*3*9"}}) import datetime y,M,d,h,m,s = 2016,2,13,18,30,0 d = datetime.datetime(y,M,d,h,m,s) delta = datetime.timedelta(hours=8) d = d-delta #logs = col_col.find( {"data":{"$gt":d} } ) #logs = col_col.find( {"message":re.compile("hi")} ) logs = col_col.find( {"$and": [{"message":re.compile("hi")}, {"data":{"$gt":d} }]} ) c = logs.count() for l in logs: print l print "count:", c print "END!"