MongoDB与Python调用

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)

参考 :http://www.cnblogs.com/hhh5460/p/5838516.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python可以使用多种方式与数据库进行交互,包括使用原生数据库API、使用ORM框架和使用HTTP接口等方式。 1. 使用原生数据库API Python提供了许多原生数据库API,可以直接使用这些API与数据库进行交互。例如,可以使用MySQLdb库与MySQL数据库进行交互,使用psycopg2库与PostgreSQL数据库进行交互,使用pyodbc库与Microsoft Access数据库进行交互等。 以下是使用MySQLdb库与MySQL数据库进行交互的示例代码: ```python import MySQLdb # 连接MySQL数据库 connection = MySQLdb.connect(host='localhost', user='your_username', passwd='your_password', db='your_database') # 获取游标 cursor = connection.cursor() # 执行SQL查询 cursor.execute('SELECT * FROM your_table_name') # 获取查询结果 results = cursor.fetchall() # 关闭游标和连接 cursor.close() connection.close() ``` 2. 使用ORM框架 ORM框架可以将数据库操作转换为Python对象的操作,使得操作更加简单和直观。常用的Python ORM框架包括SQLAlchemy、Django ORM、Peewee等。 以下是使用SQLAlchemy与MySQL数据库进行交互的示例代码: ```python from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker # 连接MySQL数据库 engine = create_engine('mysql+mysqldb://your_username:your_password@localhost/your_database') # 创建会话 Session = sessionmaker(bind=engine) session = Session() # 查询数据 results = session.query(YourModel).all() # 关闭会话 session.close() ``` 3. 使用HTTP接口 有些数据库提供了HTTP接口,可以通过HTTP请求与数据库进行交互。例如,可以使用MongoDB的REST API与MongoDB数据库进行交互。 以下是使用Python的requests库与MongoDB REST API进行交互的示例代码: ```python import requests # 查询数据 response = requests.get('http://localhost:28017/your_database/your_collection/_find') # 获取查询结果 results = response.json() ``` 以上是几种常见的Python与数据库交互的方式,可以根据实际情况选择合适的方式进行操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值