1.mongodb安装
参考官方tutorials
2.mongodb管理
# 1.创建数据库
use DATABASE_NAME
# 2.查看所有数据库
show dbs
# 3.删除数据库
# 先切换到要删除的数据库,再执行删除
use test_database
db.dropDatabase()
# 1.创建集合
db.createCollection("test_collection")
# 2.查看所有集合
show collections
# 3.删除集合
db.test_coll.drop()
3.python操作mongodb
import pymongo
# 1.连接mongodb
client = pymongo.MongoClient(host='localhost', port=27017)
# client = pymongo.MongoClient('mongodb://localhost:27017/')
# 2.获取数据库,
db = client.test
# db = Client['test_database']
# 3.获取Collection
collection = db.test_coll1
student1 = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '20170202',
'name': 'Mike',
'age': 21,
'gender': 'male'
}
# 4.增
result = collection.insert([student1,student2])
# 5.查
result5 = collection.find_one({'name': 'Mike'})
# 6.改
result6 = collection.find_one({'name': 'Jordan'})
result6['age']=24
res = collection.update({'name': 'Jordan'}, result6)
# 7.删
result7 = collection.remove({'name': 'Mike'})
# collection.delete_one({'name': 'Kevin'})
# collection.delete_many({'age': {'$lt': 25}})
3.mongodb脚本监控
# encoding:utf-8
# mongodb监控探针
from pymongo import MongoClient
import time
import pprint
import urllib
import sendlib
mg_uri = 'mongodb://root:%s@10.10.139.22,10.19.43.245' % urllib.quote('PASSWORD')
def check(uri):
conn = MongoClient(host=mg_uri, socketTimeoutMS=3000, serverSelectionTimeoutMS=3000, connectTimeoutMS=3000)
db = conn.admin
rf = True
try:
db.command("replSetGetStatus")
except Exception, e:
rf = Falses
return rf
def monitor(data_map):
for ips, pwd in data_map.iteritems():
mg_uri = 'mongodb://root:%s@%s' % (urllib.quote(pwd), ips)
rf = check(mg_uri)
if rf == False:
error_info = 'Mongodb [%s]连接失败' % ips
title = '[监控][Mongodb][连接失败]'
to = 'warning.op@sfz001.com'
sendlib.send(title, error_info, to)
if __name__ == '__main__':
data_map = {'10.10.139.22': '******',
'10.19.43.245': '******',
'10.10.139.22': '******',
'10.10.131.179': '******'}
monitor(data_map)