1 在Ubuntu下安装
1.1 安装MongoDB包:
# apt-get install mongodb-server mongodb-clients python-pymongo
安装完成后,mongod进程后启动:
root@ubuntu:~# ps -ef | grep mongo
mongodb 2122 1 14 16:39 ? 00:00:06 /usr/bin/mongod --config /etc/mongodb.conf
停止与重启:
root@ubuntu:~# service mongodb stop
mongodb stop/waiting
root@ubuntu:~# ps -ef | grep mongodb
root 1465 1418 0 16:50 pts/0 00:00:00 grep --color=auto mongodb
root@ubuntu:~# service mongodb start
mongodb start/running, process 1475
root@ubuntu:~# ps -ef | grep mongodb
mongodb 1475 1 2 16:50 ? 00:00:00 /usr/bin/mongod --config /etc/mongodb.conf
1.2 配置
1 使用的默认的端口号27017打开数据库
root@ubuntu:~# ss -antp | grep 27017
LISTEN 0 128 127.0.0.1:27017 *:* users:(("mongod",1100,9))
2 日志文件:
/var/log/mongodb/mongodb.log
3 bin下的相关命令
root@ubuntu:~# ls /usr/bin/mong*
/usr/bin/mongo /usr/bin/mongoexport /usr/bin/mongooplog /usr/bin/mongos /usr/bin/mongotop
/usr/bin/mongod /usr/bin/mongofiles /usr/bin/mongoperf /usr/bin/mongosniff
/usr/bin/mongodump /usr/bin/mongoimport /usr/bin/mongorestore /usr/bin/mongostat
其中,启动数据库只需要两个命令mongod和mongo:
mongod:是mongoDB数据库进程本身
mongo:是命令行shell客户端
2 使用shell客户端访问
2.1 使用
root@ubuntu:~# mongo
MongoDB shell version: 2.4.9
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
>
> show dbs
local 0.078125GB
> db
test
>
>
>
> help
db.help() help on db methods
db.mycoll.help() help on collection methods
sh.help() sharding helpers
rs.help() replica set helpers
help admin administrative help
help connect connecting to a db help
help keys key shortcuts
help misc misc things to know
help mr mapreduce
show dbs show database names
show collections show collections in current database
show users show users in current database
show profile show most recent system.profile entries with time >= 1ms
show logs show the accessible logger names
show log [name] prints out the last segment of log in memory, 'global' is default
use <db_name> set current database
db.foo.find() list objects in collection foo
db.foo.find( { a : 1 } ) list objects in foo where a == 1
it result of the last line evaluated; use to further iterate
DBQuery.shellBatchSize = x set default number of items to display on shell
exit quit the mongo shell
> show collections
> use local
switched to db local
> db
local
> show collections
startup_log
> db.startup_log.find()
...
> show dbs;
local 0.078125GB
test (empty)
参考:http://www.runoob.com/mongodb/mongodb-tutorial.html
2.2 DB shell数据常用操作
当创建一个集合(table)的时候会自动创建当前数据库
1. 超级用户相关:
#增加或修改用户密码
db.addUser('admin','pwd')
#查看用户列表
db.system.users.find()
#用户认证
db.auth('admin','pwd')
#删除用户
db.removeUser('mongodb')
#查看所有用户
show users
#查看所有数据库
show dbs
#切换/创建数据库
use yourDB;
#查看所有的collection
show collections
#查看各collection的状态
db.printCollectionStats()
#查看主从复制状态
db.printReplicationInfo()
#修复数据库
db.repairDatabase()
#设置记录profiling,0=off 1=slow 2=all
db.setProfilingLevel(1)
#查看profiling
show profile
#拷贝数据库
db.copyDatabase('mail_addr','mail_addr_tmp')
#删除collection
db.mail_addr.drop()
#删除当前的数据库
db.dropDatabase()
2. 客户端连接
/usr/local/mongodb/bin/mongo user_addr -u user -p 'pwd'
3. 增删改
#存储嵌套的对象
db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
#存储数组对象 db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
#根据query条件修改,如果不存在则插入,允许修改多条记录
db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
#删除yy=5的记录
db.foo.remove({'yy':5})
#删除所有的记录
db.foo.remove()
4. 索引
增加索引:1(ascending),-1(descending)
db.things.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
#索引子对象
db.user_addr.ensureIndex({'Al.Em': 1})
#查看索引信息
db.deliver_status.getIndexes()
db.deliver_status.getIndexKeys()
#根据索引名删除索引
db.user_addr.dropIndex('Al.Em_1')
5. 查询
查找所有
db.foo.find()
#查找一条记录
db.foo.findOne()
#根据条件检索10条记录
db.foo.find({'msg':'Hello 1'}).limit(10)
#sort排序 db.deliver_status.find({'From':'yushunzhi@sohu.com'}).sort({'Dt',-1}) db.deliver_status.find().sort({'Ct':-1}).limit(1)
#count操作
db.user_addr.count()
#distinct操作
db.foo.distinct('msg')
#>操作
db.foo.find({"timestamp": {"$gte" : 2}})
#子对象的查找
db.foo.find({'address.city':'beijing'})
6. 管理
查看collection数据的大小
db.deliver_status.dataSize()
#查看colleciont状态
db.deliver_status.stats()
#查询所有索引的大小
db.deliver_status.totalIndexSize()
3 Python 操作 MongoDB
#coding:utf-8
__author__ = 'hdfs'
import pymongo
from pymongo import MongoClient
client = MongoClient()
client=MongoClient('10.0.0.9',27017)
#连接mongodb数据库
client = MongoClient('mongodb://10.0.0.9:27017/')
#创建或选择数据库
db = client.test_database
#获取非系统的集合
db.collection_names(include_system_collections=False)
#创建表或获取表(集合名)
posts = db.posts
#查找单个文档
posts.find_one()
#给定条件的一个文档
posts.find_one({"author": "Mike"})
posts.save({'id':1, 'name':'test'}) # add a record
posts.insert({'id':2, 'name':'hello'}) # add a record
#使用ID查找需要ObjectID
from bson.objectid import ObjectId
post_id='5728aaa96795e21b91c1aaf0'
document = client.db.collection.find_one({'_id': ObjectId(post_id)})
import datetime
new_posts = [{"author": "Mike",
"text": "Another post!",
"tags": ["bulk", "insert"],
"date": datetime.datetime(2009, 11, 12, 11, 14)},
{"author": "Eliot",
"title": "MongoDB is fun",
"text": "and pretty easy too!",
"date": datetime.datetime(2009, 11, 10, 10, 45)}]
#插入多条记录
result = posts.insert_many(new_posts)