标签:
pymongo是操作MongoDB的python模块
# easy_install pymongo
>>> import pymongo
>>> conn = pymongo.MongoClient(host=host,port=port,tz_aware=False)
>>> conn.database_names() [u‘test1‘, u‘test2‘, u‘admin‘, u‘local‘]
>>> db = conn.get_database("db_name")
>>> db.authenticate(‘username‘, ‘password‘)
True
>>> db.collection_names() [u‘account‘, u‘role‘, u‘item‘, u‘online‘]
>>> account = db.get_collection("col_name")
>>> account.find_one()
>>> account.find_one().keys()
>>> for i in account.find(): ... print i
>>> account.find().count()
>>> for i in account.find({"name": "xxx"}): ... print i
>>> account.find().sort("name", pymongo.ASCENDING) >>> account.find().sort([("name", pymongo.ASCENDING), ("active_time", pymongo.DESCENDING)])
>>> account.insert({"name": "mike", "active_time": "20130408"})
>>> account.update({"name": "mike"}, {"$set": {"active_time": "20130408120000"}}) 注:如果数据中没有键-值"name": "mike", 会新增"active_time": "20130408120000"
>>> account.remove({"name": "mike"})
方法1. import re {‘xxx‘:re.compile(‘xxx‘)}
方法2. {‘xxx‘:{‘$regex‘:‘xxx‘}
account.find({ $or: [ { title: {$regex: ‘test‘} }, { intro: {$regex: ‘test‘} } ] })
#! /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!"
标签:
原文地址:http://www.cnblogs.com/kaituorensheng/p/5181410.html